﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using STSdb.Data;

using System.Diagnostics;

using STSdb.MTL.Utils.Serialization;
using STSdb.MTL.Utils.Async;
using STSdb.MTL.Utils.Bytes;

namespace STS_wpf_tester
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
       // public string dbPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "demo.stsdb");
        //public string dbPath = @"D:\temp\STS\demo200Ml.stsdb";
        //public string dbPath = @"D:\temp\STS\demo1_1MLN_long.stsdb";
        //public string dbPath = @"D:\temp\STS\demo1_1MLN_dts.stsdb";

        //public string dbPath = @"D:\temp\STS\demo200MLN_SSD.stsdb";
        //public string dbPath = @"S:\temp\STS\test1_SSD.stsdb";
        public string dbPath = @"D:\temp\STS\test1_SSD.stsdb";
        

        STSdb.MTL.STSdbMTLengine _sts_engine = null;

        STSdbMTL_TestManager _testMgr = null;

        public MainWindow()
        {
            InitializeComponent();

         

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //if (_sts_engine == null)
            //    _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            //_testMgr = new STSdbMTL_TestManager(_sts_engine);
        }

        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_sts_engine != null)
                _sts_engine.Dispose();
        }
           
        


        private void TestMTL()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            //System.Threading.Thread tr1 = new System.Threading.Thread(
            // () =>
            // {
            //     int threadNumber = 1;
            //     //first thread will try to acquire write lock for the table
            //     using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //     {
            //         STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //         if (tr != null)
            //             Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());

            //         System.Threading.Thread.Sleep(5000);
            //         Console.WriteLine("X1");
            //     }
            // });

            //tr1.Start();


            //System.Threading.Thread tr2 = new System.Threading.Thread(
            // () =>
            // {
            //     int threadNumber = 2;
            //     //second thread will try to acquire write lock for the table also
            //     using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //     {
            //         STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //         if (tr != null)
            //             Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());

            //         System.Threading.Thread.Sleep(5000);
            //         Console.WriteLine("X2");

            //     }
            // });

            //tr2.Start();


            /****************************************   TESTING DEADLOCKS*/

            //System.Threading.Thread tr1 = new System.Threading.Thread(
            // () =>
            // {
            //     int threadNumber = 1;
            //     try
            //     {
            //         //first thread will try to acquire write lock for the table
            //         using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //         {
            //             //tran.RegisterWriteOrReadCommitedTables(new List<string>{ "table1","table2" });

            //             STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //             if (tr != null)
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //             else
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: not found ");

            //             //System.Threading.Thread.Sleep(2000);
            //             //Console.WriteLine("X1");

            //             tr = tran.Select<long, string>("table2", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //             if (tr != null)
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //             else
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: not found ");
            //         }
            //     }
            //     catch (Exception ex)
            //     {
            //         Console.WriteLine("@@@@@@@@@@@@@ " + ex.ToString());

            //     }
                
            // });

            //tr1.Start();


            //System.Threading.Thread tr2 = new System.Threading.Thread(
            // () =>
            // {
            //     int threadNumber = 2;
            //     try
            //     {
            //         //second thread will try to acquire write lock for the table also
            //         using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //         {
            //             //tran.RegisterWriteOrReadCommitedTables(new List<string> { "table2", "table1" });

            //             STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("table2", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //             if (tr != null)
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //             else
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: not found ");

            //             //System.Threading.Thread.Sleep(2000);
            //             //Console.WriteLine("X2");

            //             tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //             if (tr != null)
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //             else
            //                 Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: not found ");
            //         }
            //     }
            //     catch (Exception ex)
            //     {
            //         Console.WriteLine("@@@@@@@@@@@@@ " + ex.ToString());
            //     }
                 
            // });

            //tr2.Start();





            /********************************************/

            //int threadNumber = 1;
            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    //tran.RegisterWriteOrReadCommitedTables(new List<string>{ "table1","table2" });

            //    STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_COMMITED, 10);

            //    if (tr != null)
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //    else
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: not found ");

            //    tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_COMMITED, 11);

            //    if (tr != null)
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //    else
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > [" + threadNumber.ToString() + "] Key: not found ");
            //}


            /********************************************/

            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    try
            //    {
            //        Dictionary<long, string> di = new Dictionary<long, string>();
            //        for (long i = 0; i < 1000000; i++)
            //        {
            //            di.Add(i, i.ToString() + "pos" + DateTime.Now.ToString());
            //        }
                        
            //        tran.InsertBatch<long, string>("tro/125/position", di);
            //        tran.Commit();
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.ToString());
            //    }                
            //}


            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("tro/125/position", STSdbMTL.TableValuesReadType.READ_UNCOMMITED, 1);

            //    if (tr != null)
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Record.ToString());
            //    else
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: not found ");
            //}



            /********************************************************/
            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("table1", STSdbMTL.TableValuesReadType.READ_UNCOMMITED, 1);

            //    if (tr != null)
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Value.ToString());
            //    else
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: not found ");
            //}

            //return;

            //long ll = 0;
            //string v = "Hello";
            //int qBulk = 10;    //inserts at once
            //int qOper = 1000000;        //how much times   qBulk * qOper = totalInsertedRecords

            ////insert bulk
            //Dictionary<long, string> div = new Dictionary<long, string>();

            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{

            //    for (int ii = 0; ii < qOper; ii++)
            //    {
            //        div.Clear();

            //        for (int i = 1; i <= qBulk; i++)
            //        {
            //            ll = ii * qBulk + i;
            //            div.Add(ll, v + ll.ToString());
            //        }
                                       

            //        tran.InsertBatch<long, string>("table1", div);
                    
            //    }

            //    Console.WriteLine("COMMITING ");                
            //    tran.Commit();
            //    //tran.RollBack();
                
            //    Console.WriteLine("COMMITED ");
            //}


            /********************************************************/

            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    //tran.Insert<long, string>("t1", 100, "100ku");
            //    //tran.Commit();

            //    //tran.Insert<STSdb.MTL.Data.XKey<long,long>, string>("t1", new XKey<long,long>(100,15), "100ku");

            //    //STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("t1", STSdbMTL.TableValuesReadType.READ_UNCOMMITED, 100);
            //    //STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("t1", STSdbMTL.TableValuesReadType.READ_COMMITED, 100);

            //    STSdbMTL.TableRow<STSdb.MTL.Data.XKey<long, long>, string> tr = tran.Select<STSdb.MTL.Data.XKey<long, long>, string>("t1", STSdbMTL.TableValuesReadType.READ_COMMITED, new XKey<long, long>(100, 15));

            //    if (tr != null)
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Value.ToString());
            //    else
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: not found ");
            //}

            //return;


            //using (STSdbMTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    tran.RegisterWriteOrReadCommitedTables("t1", "t2");

            //    //tran.Insert<long, string>("t1", 1, "1ku");
            //    //tran.Insert<long, string>("t1", 2, "2ku");
            //    //tran.Insert<long, string>("t1", 3, "3ku");
            //    //tran.Insert<long, string>("t1", 4, "4ku");
            //    //tran.Insert<long, string>("t1", 5, "5ku");
            //    //tran.Insert<long, string>("t1", 6, "6ku");

            //    //tran.Insert<long, string>("t1", 10, "20ku");
            //    //tran.Insert<long, string>("t1", 20, "20ku");

            //    //tran.Commit();

            //    foreach (var tr in tran.SelectBackward<long, string>("t1", STSdbMTL.eIsolation.READ_COMMITTED, 20, 8).Take(2))
            //    {
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Value.ToString());

            //        //if (tr.Key == 12)
            //        //    tr.Key = 10;

            //        //tr.Value = tr.Key.ToString() + "hooray";

            //    }

            //    //tran.Commit();

            //    foreach (var tr in tran.SelectBackward<long, string>("t1", STSdbMTL.eIsolation.READ_UNCOMMITTED, 20, 8).Take(2))
            //    {
            //        Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Value.ToString());
            //    }


            //    //tran.Insert<STSdb.MTL.Data.XKey<long,long>, string>("t1", new XKey<long,long>(100,15), "100ku");

            //    //STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("t1", STSdbMTL.TableValuesReadType.READ_UNCOMMITED, 100);
            //    //STSdbMTL.TableRow<long, string> tr = tran.Select<long, string>("t1", STSdbMTL.TableValuesReadType.READ_COMMITED, 100);

            //    //STSdbMTL.TableRow<STSdb.MTL.Data.XKey<long, long>, string> tr = tran.Select<STSdb.MTL.Data.XKey<long, long>, string>("t1", STSdbMTL.TableValuesReadType.READ_COMMITED, new XKey<long, long>(100, 15));

            //    //if (tr != null)
            //    //    Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + tr.Key.ToString() + "  ;;;  Value: " + tr.Value.ToString());
            //    //else
            //    //    Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: not found ");
            //}


            /****************************************************************/

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    STSdb.MTL.TableRow<long, int> tr = tran.Select<long, int>("t1", STSdb.MTL.eIsolation.READ_COMMITTED, 457);
            //    Console.WriteLine(tr.Key + " ;;; " + tr.Value);
            //}

            //return;

            //System.Threading.Thread tr1 = new System.Threading.Thread(
            // () =>
            // {
            //     //int threadNumber = 1;
            //     try
            //     {

            //         //for (int i = 0; i < 100; i++)
            //         //{
            //         using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //         {
            //             tran.RegisterWriteOrReadCommitedTables("t1");

            //             for (int i = 0; i < 10000; i++)
            //             {
            //                 STSdb.MTL.TableRow<long, int> tr = tran.Select<long, int>("t1", STSdb.MTL.eIsolation.READ_COMMITTED, 457);
            //                 tr.Value += 1;
            //             }
            //             tran.Commit();
            //         }
            //         //}

            //         Console.WriteLine("1 is done");

            //     }
            //     catch (Exception ex)
            //     {
            //         Console.WriteLine("@@@@@@@@@@@@@ " + ex.ToString());
            //     }

            // });

            //tr1.Start();


            //System.Threading.Thread tr2 = new System.Threading.Thread(
            // () =>
            // {
            //     //int threadNumber = 2;
            //     try
            //     {

            //         //for (int i = 0; i < 100; i++)
            //         //{
            //         using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //         {
            //             tran.RegisterWriteOrReadCommitedTables("t1");

            //             for (int i = 0; i < 10000; i++)
            //             {
            //                 STSdb.MTL.TableRow<long, int> tr = tran.Select<long, int>("t1", STSdb.MTL.eIsolation.READ_COMMITTED, 457);
            //                 tr.Value += 1;
            //             }

            //             tran.Commit();
            //         }
            //         //}

            //         Console.WriteLine("2 is done");

            //     }
            //     catch (Exception ex)
            //     {
            //         Console.WriteLine("@@@@@@@@@@@@@ " + ex.ToString());
            //     }

            // });

            //tr2.Start();


            /*************************************/

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    tran.test<long, int>("t1");

            //    //tran.RegisterWriteOrReadCommitedTables("t1");

            //    //for (int i = 0; i < 10000; i++)
            //    //{
            //    //    STSdb.MTL.TableRow<long, int> tr = tran.Select<long, int>("t1", STSdb.MTL.eIsolation.READ_COMMITTED, 457);
            //    //    tr.Value += 1;
            //    //}
            //    //tran.Commit();
            //}

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    tran.RegisterWriteOrReadCommittedTables("table1/mainInfo", "table1/extras");

            //    DateTime now=DateTime.Now;
            //    tran.Insert<long, string>("table1/mainInfo", now.Ticks, "serialized main info");
            //    tran.Insert<long, string>("table1/extras", now.Ticks, "serialized extras");

            //    tran.Commit();
            //}

            /*************************************/

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    try
            //    {
            //        var tr = tran.Select<long, string>("t1", STSdb.MTL.eIsolation.READ_UNCOMMITTED, 1);
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.ToString());
            //    }                

            //}

            /*************************************/

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    try
            //    {
            //        tran.InDevPlayWithSchema();
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.ToString());
            //    }

            //}
        }

        private void testSTSdbMTL()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath); //STSdb has virtual file system layer, also database file can be created from many file located in different places.

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                //transaction is started

                //we can register here tables which has to be modified, and get 100% defense from the deadlocks.

                tran.RegisterWriteOrSynchroReadTables("table1/mainInfo", "table1/extras");

                //we've reserved these two tables for mutation inside of our transaction.

                //we don't need to register anything if only one or less tables will be mutated within one transaction

                //we rows into two different tables. Tables will be created and supported automatically, if they don't exist.

                DateTime now = DateTime.Now;
                tran.Insert<long, string>("table1/mainInfo", now.Ticks, "serialized main info");
                tran.Insert<long, string>("table1/extras", now.Ticks, "serialized extras");

                //STSdb is a Key/Value Storage (complex keys are supported), so first type long is our key, second type string is our data.
                //Documentation about STSdb better to get on their website http://stsdb.com/stsdb-user-forum/

                //Then we have to commit all operations. If we don't have commit, data will not be changed
                tran.Commit(); //already in db

                //Operators have lot's of overloads, Insert, InsertBatch, SelectForward, backward etc..

                //No we want to select something.

                STSdb.MTL.TableRow<long, string> tr = tran.Select<long, string>("table1/mainInfo", STSdb.MTL.eSelectMode.READ_SYNCHRO, now.Ticks);

                //update of the value
                tr.Value = "new value";

                //update of the key
                tr.Key = 4568; //new key

                tran.Commit(); //already in db
                
                //or loop

                foreach (var row in tran.SelectBackward<long, string>("table1/mainInfo", STSdb.MTL.eSelectMode.READ, now.Ticks, 8).Take(2))
                {
                    Console.WriteLine(DateTime.Now.Ticks.ToString() + " " + DateTime.Now.ToString("mm:ss.ms") + " > Key: " + row.Key.ToString() + " ;;; Value: " + row.Value.ToString());
                }

                //with READ_COMMITTED you can be sure that you take the latest value, then you can modify it and save back, next concurrent thread will take exactly your modified value.
                //If there are concurrent threads which want to update the same table as first thread, they will have to wait.
                //Otherwise the threads which want to READ_UNCOMMITTED value, will receive them fast and in parallel with the thread who is making modification.
                //READ_UNCOMMITED - reporting style.
                //READ_COMMITED - bank account value change style.
            }

        }



        int id = 1;
        object lock_id = new object();
        private int GetId()
        {
            int rid=0;
            lock (lock_id)
            {
                rid = id;
                id++;
            }

            return rid;
        }

        private void test1()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            _testMgr = new STSdbMTL_TestManager(_sts_engine);


            DateTime now = DateTime.Now;
            Console.WriteLine("Started: {0}", now.ToString("HH:mm:ss.ms"));

            string value = "ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_";

            value += "ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_";
            value += "ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_";
            value += "ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_";
            value += "ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_";


            for (int i = 0; i < 20; i++)
            {

                this._testMgr.StartActionInThread(
                () =>
                {
                    int id = this.GetId();
                    this._testMgr.InsertBatch_LongString("t" + id.ToString(), value, 1000, 1000, id, false, false, true);
                }
                );
            }




            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    //var tr = tran.Select<long, string>("t1", STSdb.MTL.eSelectMode.READ, 2);
            //    //tran.Commit();
            //}
        }

        private void test2()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            _testMgr = new STSdbMTL_TestManager(_sts_engine);

            //string value = "ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_ABCDEFGАБВГДЕЁÖÜÄЫ1234325434@й87878rt%$_";

            //this._testMgr.InsertBatch_LongString("t1", value, 100, 1, 1, false, false, true);

            //return;

            Action read = () =>
                {
                    using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
                    {
                        //FIRST READ STILL RETURNS "OLD VALUES"
                        Console.WriteLine("read started");
                        foreach (var res in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ))
                        {
                            Console.WriteLine("k: {0}; V: {1}", res.Key, res.Value);
                            System.Threading.Thread.Sleep(200);
                        }

                        //WRITE IN THE TABLE WAS DONE IN THE MIDDLE OF THE FIRST LOOP

                        //SECOND READ ALREADY RETURNS NEW VALUES.
                        Console.WriteLine("------------------------------------rea2d started");
                        foreach (var res in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ))
                        {
                            Console.WriteLine("k: {0}; V: {1}", res.Key, res.Value);
                            System.Threading.Thread.Sleep(200);
                        }
                    }
                };

            this._testMgr.StartActionInThread(read);

             Action write = () =>
                {
                    using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
                    {
                        Console.WriteLine("write started");
                        foreach (var res in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ_SYNCHRO))
                        {
                            res.Value = DateTime.Now.ToString();
                        }
                        tran.Commit();
                        Console.WriteLine("write stopped");
                    }
                };

             this._testMgr.StartActionInThread(write);

        }


        private void test_commitInOneThread_rollBackInAnother()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            _testMgr = new STSdbMTL_TestManager(_sts_engine);

            //_testMgr.InsertBatch_LongString("t1", null, 10, 1, 1, false, true, true);

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                //tran.Insert<long, string>("t1", 1, null);
                //tran.Insert<long, string>("t1", 2, null);
                //tran.Insert<long, string>("t1", 3, "test");

                //tran.Insert<DateTime, string>("t1", new DateTime(2011, 10, 10, 10, 0, 0, 0), null);
                //tran.Insert<DateTime, string>("t1", new DateTime(2011, 10, 10, 12, 0, 0, 0), null);
                //tran.Insert<DateTime, string>("t1", new DateTime(2011, 10, 10, 14, 0, 0, 0), "test");

                //tran.Commit();

                //var max = tran.MaxRow<long, string>("t1");
                //var min = tran.MinRow<long, string>("t1");
                //var count = tran.Count<long, string>("t1");

                var max = tran.MaxRow<DateTime, string>("t1");
                var min = tran.MinRow<DateTime, string>("t1");
                var count = tran.Count<DateTime, string>("t1");
            }

            return;


            Action write = () =>
               {
                   //writing
                   using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
                   {
                       tran.Insert<long, string>("t1", 1, "xxx");
                       Console.WriteLine("sleep t1");
                       System.Threading.Thread.Sleep(5000);
                       Console.WriteLine("t1 done");

                       tran.Commit();
                   }
               };

            this._testMgr.StartActionInThread(write);

            Action read = () =>
               {
                   using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
                   {
                       Console.WriteLine("sleep t2");
                       System.Threading.Thread.Sleep(2000);
                       Console.WriteLine("t2 doing");

                       tran.Select<long, string>("t1", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
                       tran.RollBack();
                       Console.WriteLine("t2 done");
                   }
               };

            this._testMgr.StartActionInThread(read);

        }

        private void testIdentityAutoIncrement()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);           

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {

                //We want to have table with autoincrement key property.
                //First of all we need get the maximal value of the key

                //last parameter true, means that we want also register this table for modification 
                //(so the other threads who want to modify this table will have to wait till this thread is finished)
                //Threads which only want to read values will get values which were available before starting this transaction,
                //in the fastest form an dwithout waiting till this thread is finished.
                var tr = tran.MaxRow<long, string>("t1", true);
                long id = 0;

                //if row is not found then id remains 0
                if (tr != null)
                    id = tr.Key;    //otherwise maxId = tr.Key

                for (int i = 1; i <= 20; i++)
                {
                    //increasing value, increasing key by one per iteration
                    tran.Insert<long, string>("t1", id + i, "v"+i.ToString());
                }

                //Count used for the table returns quantity of the inserted records
                //If we modify this table, then modified Count will be returned
                //If we don't modify in the table then last committed by other transaction count will be returned.
                //The same works for MinRow and MaxRoe
                Console.WriteLine("Count of values: " + tran.Count<long, string>("t1"));

                //Committed
                tran.Commit();

                //Function is thread safe
            }
        }

        #region "tests with cars"

        public class Car
        {
            public Car()
            {
                this.CarId = 0;
                this.LicencePlate = String.Empty;
                this.VIN = "00000000000000000";
                this.Mileage = 0;
                this.ProductionYear = new DateTime(2000, 1, 1);
            }

            /// <summary>
            /// Will be moved into the table key
            /// </summary>
            public int CarId { get; set; }

            public string LicencePlate { get; set; }

            public string VIN { get; set; }

            /// <summary>
            /// Doubled with the info inside of VIN
            /// </summary>
            public DateTime ProductionYear { get; set; }

            public int Mileage { get; set; }

            public string Model { get; set; }
                        
        }


        private void FillDb_WithCars()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {

                //this line we add after adding the "cars/licensePlate" table
                //tran.RegisterWriteOrSynchroReadTables("cars", "cars/licensePlate");
                    

                var tr = tran.MaxRow<int, Car>("cars", true);
                int id = 0;

                //if row is not found then id remains 0
                if (tr != null)
                    id = tr.Key;    //otherwise maxId = tr.Key

                Random rnd=new Random();
                int mileage = 0;

                Car car = null;

                for (int ii = 0; ii < 20; ii++)
                {
                    mileage = rnd.Next(10000, 250000);
                    id += 1;
                    car = new Car()
                    {
                        CarId = id,
                        Mileage = mileage,
                        LicencePlate = "MY_FIRMA_" + id.ToString(),
                        Model = "BMW",
                        ProductionYear = DateTime.Now,
                        VIN = String.Format("{0:00000}0000{1}", mileage, "BMW")
                    };

                    tran.Insert<int, Car>("cars", id, car);
                    
                    
                    //THIS ALL APPEARS ONLY IF WE'VE ADDED new index for the car table
                    //here we also must update the index cars/licensePlate


                    //Car info can be changed, but not necessarily the licensePlate info has to be changed.
                    //Car information can be changed only if we update, but not if we insert.
                    //So, probably, to have two different methods one for insert and second for the update is a good idea.
                    //When car information changes there is a probability that licensePlate will not be updated so 
                    //we don't need to update table cars/licensePlate

                    //INSERT CASE
                    //tran.Insert<string, int>("cars/licensePlate", car.LicencePlate, car.CarId);

                    //UPDATE CASE
                    //first get existing element
                    //var carToUpdateRow = tran.Select<int, Car>("cars", STSdb.MTL.eSelectMode.READ_SYNCHRO, 12);

                    //if (carToUpdateRow.Exists)
                    //{
                    //    //checking if car for update changed it's licensePlate
                    //    if (car.LicencePlate != carToUpdateRow.Value.LicencePlate)
                    //    {
                    //        //yes, license plate was changed
                    //        var car_licensePlateIndex = tran.Select<string, int>("cars/licensePlate", STSdb.MTL.eSelectMode.READ_SYNCHRO, carToUpdateRow.Value.LicencePlate);
                            
                    //        //doesn'tmetter if it was found or not we update it in any way
                    //        car_licensePlateIndex.Key = car.LicencePlate;
                    //    }

                    //    //then we update cars
                    //    carToUpdateRow.Value = car;
                    //}

                    ////that'S all for the first index
                    /*****************************************/

                }
                
                //Committed
                tran.Commit();           
            }
        }


        private void ReadCars()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                foreach (var car in tran.SelectForward<int,Car>("cars",STSdb.MTL.eSelectMode.READ))
                {
                    
                }
            }
        }


        private class SupportedIndex
        {

            public SupportedIndex()
            {
                this.Name = String.Empty;
                this.Finished = false;
                this.udtStart = DateTime.UtcNow;
                this.udtStop = DateTime.UtcNow;
            }

            public string Name { get; set; }
            /// <summary>
            /// indicates that proceudre was finished
            /// </summary>
            public bool Finished { get; set; }
            /// <summary>
            /// UTC Date Time of procedure start
            /// </summary>
            public DateTime udtStart { get; set; }
            /// <summary>
            /// UTC Date Tiem of procedure stop
            /// </summary>
            public DateTime udtStop { get; set; }
        }

        private void SupportNewIndex()
        {
            this.SupportNewIndex_cars_licencePlate();
        }

        private void SupportNewIndex_cars_licencePlate()
        {
            //CHECKING IF SUPPORT WSA ALREADY DONE

            //SupportNewIndex procedure must run only once so we have to make somewhere a record that this procuderes once was started
            //we need to create new index for fast search by LicencePlate

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                var tr = tran.Select<string, SupportedIndex>("SupportedIndexes", STSdb.MTL.eSelectMode.READ_SYNCHRO, "cars/licensePlate");
                if (tr.Exists)
                {
                    if (tr.Value.Finished)
                        return; //index was already createded
                }

                tr.Value = new SupportedIndex()
                {
                     Name = "cars/licensePlate"
                };

                tran.Commit();
            }


            //CREATING INDEX SELF

            //steps iterating over all existing values via standart read lock,
            //the values which are inserted in the table in the moment while we are iterating, will be handeld alread by new INSERT CAR procedure, 
            //because while insert we have to support already 2 tables

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                foreach (var car in tran.SelectForward<int, Car>("cars", STSdb.MTL.eSelectMode.READ))
                {
                    tran.Insert<string, int>("cars/licensePlate", car.Value.LicencePlate, car.Key);
                }

                tran.Commit();
            }

            //FINILIZING SUPPORT TABLE

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                var tr = tran.Select<string, SupportedIndex>("SupportedIndexes", STSdb.MTL.eSelectMode.READ_SYNCHRO, "cars/licensePlate");
                tr.Value.Finished = true;
                tr.Value.udtStop = DateTime.UtcNow;
                //we changed the calss inside tr.Value, we have to call tr.Update() explicitely, so system knows that this value was updated.
                //for now, I don't know how to get rid of this call in such case.
                //the same effect can be achieved if we say tr.Value = tr.Value;
                tr.Update();
                tran.Commit();
            }
        }


        private void SearchingCarByLicensePlate()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                var tr = tran.Select<string, int>("cars/licensePlate", STSdb.MTL.eSelectMode.READ, "MY_FIRMA_15");
                if (tr.Exists)
                {
                    var trcar = tran.Select<int, Car>("cars", STSdb.MTL.eSelectMode.READ, tr.Value);
                    if (trcar.Exists)
                    {
                        //here is a car
                        var car = trcar.Value;
                    }
                }
            }
        }

        #endregion



        #region "CCreate Many tables"
        private void CreateManyTabels()
        {
            //145 Kb per table...with content int, string>("t" + i.ToString(), 1, "a"; Created 2000 tables, took 121 sec, 145MB RAM, 290MB HDD space...
            Stopwatch sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < 2; i++)
            {
                using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
                {
                    tran.Insert<int, string>("t" + i.ToString(), 1, "a");
                    tran.Commit();
                }
            }

            sw.Stop();
            Console.WriteLine("Ms: {0}", sw.ElapsedMilliseconds);
        }
        #endregion


        private void InsertStrings()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                for (int i = 0; i < 100000; i++)
                //for (int i = 0; i < 4000000; i++)
                //for (int i = 0; i < 40000000; i++)
                {
                    tran.Insert<string, int>("t1", i.ToString(), i);
                }
                tran.Commit();
            }

            Console.WriteLine("DONE");
        }

        private void InsertInts()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                for (int i = 0; i < 1; i++)
                //for (int i = 0; i < 100000; i++)
                //for (int i = 0; i < 4000000; i++)
                //for (int i = 0; i < 40000000; i++)
                {
                    tran.Insert<int, int>("t1", i, i);
                }
                tran.Commit();
            }

            Console.WriteLine("DONE");
        }

        private void InsertBytes(Encoding encoding)
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                System.Diagnostics.Stopwatch sw = new Stopwatch();
                sw.Start();

                ////for (int i = 0; i < 255; i++)
                //for (int i = 0; i < 100000; i++)
                ////for (int i = 0; i < 4000000; i++)
                ////for (int i = 0; i < 40000000; i++)
                //{
                //      tran.Insert<byte[], int>("t1", new byte[]{(byte)i}, i);
                //}
                //tran.Commit();

                //Console.WriteLine("DONE" + tran.Select<byte[],int>("t1",STSdb.MTL.eSelectMode.READ,new byte[]{142}).Value);

                //List<string> strings =new List<string> { "Hello", "Kuku", "Aida" };
                //byte[] b=null;
                //int i = 0;
                //foreach (var s in strings)
                //{
                //    b = System.Text.Encoding.UTF8.GetBytes(s);
                //    tran.Insert<byte[], int>("t1", b, i);
                //    i++;
                //}

                //tran.Insert<byte[], int>("t1", new byte[] { 100, 101, 102, 100 }, 104);
                //tran.Insert<byte[], int>("t1", new byte[] { 100, 101, 103 }, 103);
                //tran.Insert<byte[], int>("t1", new byte[] { 100, 101, 102 }, 102);
                //tran.Insert<byte[], int>("t1", new byte[] { 100, 101, 101 }, 101);

                //byte[] b = null;
                //for (int i = 0; i < 100000; i++)
                //{
                //    b = System.Text.Encoding.UTF8.GetBytes(i.ToString());
                //    Array.Reverse(b, 0, b.Length);
                //    tran.Insert<byte[], int>("t1", b, i);
                //}




                
                //List<string> strings = new List<string> { "Kuku", "Zello", "Aida", "Hello", "Kukuz" };
                //List<string> strings = new List<string> { "Kuku", "Zell", "Aida", "HeLi", "Kukr" };

                //List<string> strings = new List<string> { "a", "aa", "aaa", "aaa", "aaaa", "aaaaa", "aaaaaa" };
                //List<string> strings = new List<string> { "1", "2", "1000", "1001", "10000"};
                //byte[] b = null;
                //int i = 0;
                //foreach (var s in strings)
                //{
                //    b = encoding.GetBytes(s);
                //    Array.Reverse(b, 0, b.Length);
                //    b = AddLeadingNulls(99, b);
                //    tran.Insert<byte[], int>("t1", b, i);
                //    i++;
                //}






                byte[] b = null;
                int maxByteCount = encoding.GetMaxByteCount(7);
                maxByteCount = 7;
                for (int i = 0; i < 100000; i++)
                //for (int i = 0; i < 4000000; i++)
                {
                    b = encoding.GetBytes(i.ToString());
                    Array.Reverse(b, 0, b.Length);
                    b = AddLeadingNulls(maxByteCount, b);
                    tran.Insert<byte[], int>("t1", b, i);
                }

                               


                //for (int i = 0; i < 4000000; i++)
                //{
                //    tran.Insert<int, int>("t1", i, i);
                //}




                tran.Commit();
                sw.Stop();
                Console.WriteLine("DONE " + sw.ElapsedMilliseconds.ToString() + ".ms");
            }


            //System.Diagnostics.Stopwatch sw = new Stopwatch();
            //sw.Start();

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    for (int i = 0; i < 4000000; i++)
            //    {
            //        b = Encoding.ASCII.GetBytes(i.ToString());
            //        Array.Reverse(b, 0, b.Length);
            //        b = AddLeadingNulls(7, b);
            //        tran.Insert<byte[], int>("t1", b, i);
            //    }
            //    tran.Commit();
            //}
            //sw.Stop();
            //Console.WriteLine("DONE. {0} ms", sw.ElapsedMilliseconds);
            
        }

        private byte[] AddLeadingNulls(int size, byte[] ib)
        {
            byte[] r = new byte[size];

            //or just
            //Array.Copy(ib, 0, r, (size - ib.Length), ib.Length);

            for (int i = 0; i < (size - ib.Length); i++)
            {
                r[i] = 0;
            }

            int j = 0;
            for (int i = (size - ib.Length); i < size; i++)
            {
                r[i] = ib[j];
                j++;
            }

            return r;
        }

        private byte[] RemoveLeadingNulls(byte[] ib)
        {
            byte[] ta=null;

            for (int i = 0; i < ib.Length; i++)
            {
                if (ib[i] != 0)
                {
                    ta = new byte[ib.Length - i];
                    Array.Copy(ib, i, ta, 0, ib.Length - i);
                    return ta;
                }
            }
                        
            //return System.Text.Encoding.UTF8.GetBytes(String.Empty);
            return new byte[] { };
        }

        private void SelectBytesBackward(Encoding encoding)
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                byte[] b = null;

                //foreach (var tr in tran.SelectBackward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ, new byte[] { 150 }).Take(10))                
                foreach (var tr in tran.SelectBackward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
                {
                    b = tr.Key;
                    b = RemoveLeadingNulls(b);
                    Array.Reverse(b, 0, b.Length);
                    Console.WriteLine("Key: {0}; V: {1}; KV: {2}", BitConverter.ToString(tr.Key), tr.Value, encoding.GetString(b));
                }
            }

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    byte[] b = null;
              
            //    foreach (var tr in tran.SelectBackward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
            //    {
            //        b = tr.Key;
            //        b = RemoveLeadingNulls(b);
            //        Array.Reverse(b, 0, b.Length);
            //        Console.WriteLine("Key: {0}; V: {1}; KV: {2}", BitConverter.ToString(tr.Key), tr.Value, Encoding.UTF8.GetString(b));
            //    }
            //}
        }

        private void SelectBytesForward(Encoding encoding)
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                byte[] b = null;
                //foreach (var tr in tran.SelectBackward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ, new byte[] { 150 }).Take(10))
                foreach (var tr in tran.SelectForward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
                {
                    b = tr.Key;
                    //Array.Reverse(b, 0, b.Length);
                    b = RemoveLeadingNulls(b);
                    Array.Reverse(b, 0, b.Length);
                    Console.WriteLine("Key: {0}; V: {1}; KV: {2}", BitConverter.ToString(tr.Key), tr.Value, encoding.GetString(b));
                }
            }

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    byte[] b = null;                
            //    foreach (var tr in tran.SelectForward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
            //    {
            //        b = tr.Key;                    
            //        b = RemoveLeadingNulls(b);
            //        Array.Reverse(b, 0, b.Length);
            //        Console.WriteLine("Key: {0}; V: {1}; KV: {2}", BitConverter.ToString(tr.Key), tr.Value, Encoding.UTF8.GetString(b));
            //    }
            //}
        }

        //private void SelectBytesForward(Encoding encoding)
        //{
        //    using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
        //    {
        //        byte[] b = null;
        //        //foreach (var tr in tran.SelectBackward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ, new byte[] { 150 }).Take(10))
        //        foreach (var tr in tran.SelectForward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
        //        {
        //            b = tr.Key;
        //            //Array.Reverse(b, 0, b.Length);
        //            b = RemoveLeadingNulls(b);
        //            Array.Reverse(b, 0, b.Length);
        //            Console.WriteLine("Key: {0}; V: {1}; KV: {2}", BitConverter.ToString(tr.Key), tr.Value, encoding.GetString(b));
        //        }
        //    }
        //}


        private void InsertAndSelectString()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                List<string> strings = new List<string> { "1", "2", "1000", "1001", "10000" };
                int i = 0;
                foreach (var s in strings)
                {                   
                    tran.Insert<string, int>("t1", s, i);
                    i++;
                }

                tran.Commit();
            }

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<string, int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
                {
                    Console.WriteLine("Key: {0}; V: {1}; ", tr.Key, tr.Value);
                }
            }

            Console.WriteLine("-----");

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                foreach (var tr in tran.SelectBackward<string, int>("t1", STSdb.MTL.eSelectMode.READ).Take(50))
                {
                    Console.WriteLine("Key: {0}; V: {1}; ", tr.Key, tr.Value);
                }
            }
        }



        #region "Initial tables properties settings"

        bool tablesAreInititalized = false;
        private void InitTables()
        {
            if (tablesAreInititalized)
                return;

            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            tablesAreInititalized = true;


#region "test with strings"

            //Initializing table t1
            STSdb.MTL.TableProperties<byte[], int> tp = new STSdb.MTL.TableProperties<byte[], int>()
            {
                BlockCapacity = 1024,
                CacheCapacity = 1,
                KeyMap = null,
                RecordPersist = null
            };
            
            _sts_engine.Scheme.SetTableProperties<byte[], int>("t1", tp);
#endregion

        }
        #endregion


        #region "test DYNAMIC TYPES type conversions"

        private void insertCar()
        {
           

            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                tran.Insert<int, STS_wpf_tester.XCar>("cars", 1, new STS_wpf_tester.XCar()
               {
                    CarId = 1,
                    LicencePlate = "cc"
               });

                tran.Insert<int, STS_wpf_tester.XCar>("cars", 3, new STS_wpf_tester.XCar()
                {
                    CarId = 3,
                    LicencePlate = "cc3"
                });


                tran.Insert<int, STS_wpf_tester.XCar>("cars", 15, new STS_wpf_tester.XCar()
                {
                    CarId = 15,
                    LicencePlate = "cc15"
                });

               tran.Commit();
            }
        }

        private void SelectCar()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {
                Type myKey = Type.GetType("System.Int32");  //getting type for int
                Type myValue = Type.GetType("STS_wpf_tester.XCar"); //getting type for STS_wpf_tester.XCar

                System.Reflection.MethodInfo mi = (System.Reflection.MethodInfo)STSdb.MTL.CachedReflections.GetObject("Transaction/Method/SelectSimple");

                //CONVERTING METHOD TO GENERIC
                var mi_constructed = mi.MakeGenericMethod(myKey, myValue);

                object[] pars = new object[3];
                pars[0] = "cars";   //we supply table name as string
                //pars[1] = STSdb.MTL.eSelectMode.READ;
                pars[1] = Enum.Parse(typeof(STSdb.MTL.eSelectMode), "READ");  //we supply select mode as string can be also READ_SYNCHRO
                pars[2] = Convert.ChangeType("1", myKey);     //searching key, key we supply as string     

                var tr = mi_constructed.Invoke(tran, pars);

                Type tbrOpenType = typeof(STSdb.MTL.TableRow<,>);                                   //THESE CAN LIVE AS STATIC METHOD IN TableRowClass
                Type tbrCloseType = tbrOpenType.MakeGenericType(myKey, myValue);                    //
                
                var tbrKeyExists = STSdb.MTL.CachedReflections.Get_FastPropertyAccessor(tr, tbrCloseType, "Exists");


                if (!(bool)tbrKeyExists)
                {
                    Console.WriteLine("NO RESULT");
                    return;             //NO RESULT FOUND IN DB //WE CAN SEND RESULT VALUE VIA WIRES
                }

                var tbrValue = STSdb.MTL.CachedReflections.Get_FastPropertyAccessor(tr, tbrCloseType, "Value");
                var tbrKey = STSdb.MTL.CachedReflections.Get_FastPropertyAccessor(tr, tbrCloseType, "Key");

                //SERIALIZING VALUE TO STRING

                string serializedValue1 = "NULL"; //MEANS DEFAULT NULL VALUE
                if (tbrValue != null)
                {
                    serializedValue1 = SerializeXml(tbrValue);
                }

                //also possible to make like this
                //serializedValue1 = SerializeXml(tr);

            }
        }

       
        
        private void SelectForwardCar()
        {
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {




                //string res = tran.NonGenerics.Select("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ", "1");

                //string res = tran.NonGenerics.SelectForward("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ", 1);
                //string res = tran.NonGenerics.SelectForwardStartKey("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ","3",5);
                //string res = tran.NonGenerics.SelectForwardStartEndKey("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ","1", "3", 5);


                //string res = tran.NonGenerics.SelectBackward("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ", 2);
                //string res = tran.NonGenerics.SelectBackwardLastKey("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ", "3", 5);
                //string res = tran.NonGenerics.SelectBackwardLastFirstKey("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ", "20", "3", 5);

                //string res = tran.NonGenerics.Count("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ");
                //string res = tran.NonGenerics.MaxRow("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ");
                //string res = tran.NonGenerics.MinRow("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ");

                return;



                Type myKey = Type.GetType("System.Int32");  //getting type for int
                Type myValue = Type.GetType("STS_wpf_tester.XCar"); //getting type for STS_wpf_tester.XCar

                System.Reflection.MethodInfo mi = (System.Reflection.MethodInfo)STSdb.MTL.CachedReflections.GetObject("Transaction/Method/SelectForward");

                //CONVERTING METHOD TO GENERIC
                var mi_constructed = mi.MakeGenericMethod(myKey, myValue);

                object[] pars = new object[2];
                pars[0] = "cars";   //we supply table name as string
                //pars[1] = STSdb.MTL.eSelectMode.READ;
                pars[1] = Enum.Parse(typeof(STSdb.MTL.eSelectMode), "READ");  //we supply select mode as string can be also READ_SYNCHRO
                //pars[2] = Convert.ChangeType("1", myKey);     //searching key, key we supply as string     

                var tr = mi_constructed.Invoke(tran, pars);

                
                Type tp2 = typeof(STSdb.MTL.TableRow<,>);
                Type tb2c = tp2.MakeGenericType(myKey, myValue);

                //Type tp1 = typeof(IEnumerable<>);
                //Type tp1c = tp1.MakeGenericType(tb2c);

                Type lst = typeof(List<>);
                Type lst2c = lst.MakeGenericType(tb2c);

                //object olist = Activator.CreateInstance(typeof(List<STSdb.MTL.TableRow<int,STS_wpf_tester.XCar>>));//.CreateInstance(lst2c);

                //Creating List<STSdb.MTL.TableRow<int,STS_wpf_tester.XCar>>
                object olist = Activator.CreateInstance(lst2c);   


                foreach (object o in (tr as IEnumerable))       //namespace System.Collections;
                {
                    ((IList)olist).Add(o);
                    //here can be Take implemented...if then break;
                }

                string ss = SerializeXml(olist);
                //foreach (var uzi in (IEnumerable<STSdb.MTL.TableRow<int, STS_wpf_tester.XCar>>)tr)
                //{

                //}
                return;

                //var tr = mi_constructed.Invoke(tran, pars);

                //Type tbrOpenType = typeof(STSdb.MTL.TableRow<,>);                                   //THESE CAN LIVE AS STATIC METHOD IN TableRowClass
                //Type tbrCloseType = tbrOpenType.MakeGenericType(myKey, myValue);                    //

                //var tbrKeyExists = STSdb.MTL.CachedReflections.Get_FastPropertyAccessor(tr, tbrCloseType, "Exists");


                //if (!(bool)tbrKeyExists)
                //{
                //    Console.WriteLine("NO RESULT");
                //    return;             //NO RESULT FOUND IN DB //WE CAN SEND RESULT VALUE VIA WIRES
                //}

                //var tbrValue = STSdb.MTL.CachedReflections.Get_FastPropertyAccessor(tr, tbrCloseType, "Value");
                //var tbrKey = STSdb.MTL.CachedReflections.Get_FastPropertyAccessor(tr, tbrCloseType, "Key");

                ////SERIALIZING VALUE TO STRING

                //string serializedValue1 = "NULL"; //MEANS DEFAULT NULL VALUE
                //if (tbrValue != null)
                //{
                //    serializedValue1 = SerializeXml(tbrValue);
                //}

                //also possible to make like this
                //serializedValue1 = SerializeXml(tr);

            }
        }




        private void SelectCar_test()
        {
            //FIRST WE HAVE INSERTED CAR, NOW WE WANT TO RETRIEVE THEM, BUT SUPPLYING ONLY STRINGS as parameters, to make it working via wires

            //using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            //{
            //    var tr = tran.Select<int, STS_wpf_tester.XCar>("cars", STSdb.MTL.eSelectMode.READ, 1);

            //    Console.WriteLine("K:{0}; V:{1}", tr.Key, tr.Value);
            //}

            

            //THE SAME WITH DYNAMICALLY SUPPLIED PARAMETERS

            //DYNAMIC PARAMETERS CASTING For Select
            using (STSdb.MTL.Transaction tran = _sts_engine.GetTransaction())
            {

                //MAKE REFLECTION FASTER WITH  http://fasterflect.codeplex.com/
 
                //http://www.codeproject.com/KB/cs/fast_dynamic_properties.aspx
                //or http://www.codeproject.com/KB/library/fasterflect_.aspx
                //or http://weblogs.asp.net/jeffreyzhao/archive/2009/01/27/fast-reflection-library.aspx

                //expression trees serializer http://archive.msdn.microsoft.com/exprserialization
                //http://interlinq.codeplex.com/
                //http://expressiontree.codeplex.com/
                //http://metalinq.codeplex.com/
                //http://iqtoolkit.codeplex.com

                //RECEIVING REMOTE COMMAND SELECT WITH STRING PARAMETERS

                //STSdb.MTL.TransactionReflections.Init();

                //Type ex = tran.GetType();       //..can be called only once and cached
                Type ex = typeof(STSdb.MTL.Transaction);

                //Type myKey = typeof(int); //or
                Type myKey = Type.GetType("System.Int32");  //getting type for int
                Type myValue = Type.GetType("STS_wpf_tester.XCar"); //getting type for STS_wpf_tester.XCar



                //System.Reflection.MethodInfo mi = ex.GetMethod("Select");   //getting method select



                //or use direct search for overloaded methods like this:

                //var methods = ex.GetMethods();
                //methods[12].ToString()	"System.Collections.Generic.IEnumerable`1[STSdb.MTL.TableRow`2[T,T1]] SelectForward[T,T1](System.String, STSdb.MTL.eSelectMode)"	string
		        //methods[13].ToString()	"System.Collections.Generic.IEnumerable`1[STSdb.MTL.TableRow`2[T,T1]] SelectForward[T,T1](System.String, STSdb.MTL.eSelectMode, T)"	string
                //in our case
                //methods[11].ToString()	"STSdb.MTL.TableRow`2[T,T1] Select[T,T1](System.String, STSdb.MTL.eSelectMode, T)"	string


                //SO IN OUR CASE IT CAN BE  //getting method select...can be called only once and cached
                System.Reflection.MethodInfo mi = ex.GetMethods().Where(r => r.ToString().Equals("STSdb.MTL.TableRow`2[T,T1] Select[T,T1](System.String, STSdb.MTL.eSelectMode, T)")).First();

                //System.Reflection.MethodInfo mi = (System.Reflection.MethodInfo)STSdb.MTL.CachedReflections.GetObject("Transaction/Method/SelectSimple");


                //var mi_constructed = mi.MakeGenericMethod(typeof(int), typeof(STS_wpf_tester.XCar));

                //CONVERTING METHOD TO GENERIC
                var mi_constructed = mi.MakeGenericMethod(myKey, myValue); //...can be called once

                //PREPEARING METHOD PARAMTERS FROM STRINGS
                object[] pars=new object[3];
                pars[0] = "cars";   //we supply table name as string
                //pars[1] = STSdb.MTL.eSelectMode.READ;
                pars[1] = Enum.Parse(typeof(STSdb.MTL.eSelectMode), "READ");  //we supply select mode as string can be also READ_SYNCHRO
                pars[2] = Convert.ChangeType("1", myKey);     //searching key, key we supply as string                
                //pars[2] = Convert.ChangeType("2", myKey);     //searching key, key we supply as string                

                

                //EXECUTING METHOD, IT WILL RETURN GENERIC TABLEROW
                //Executing method select on table "cars" in STSdb.MTL.eSelectMode.READ with parameter key 1
                var tr = mi_constructed.Invoke(tran, pars);
                //the same as 
                //STSdb.MTL.TableRow<int, STS_wpf_tester.XCar> tr1 = (STSdb.MTL.TableRow<int, STS_wpf_tester.XCar>)mi_constructed.Invoke(tran, pars);

                //received parameter must be converted to

                //string serializedValue = SerializeXml(((STSdb.MTL.TableRow<int, STS_wpf_tester.XCar>)tr).Value);

                //CASTING TABLE ROW TO GENERIC
                //...making it dynamic
                Type tbrOpenType = typeof(STSdb.MTL.TableRow<,>);                                   //THESE CAN LIVE AS STATIC METHOD IN TableRowClass
                Type tbrCloseType = tbrOpenType.MakeGenericType(myKey, myValue);                    //


                //***************************************   tbrCloseType must be cached together with propExists TO AVOID MEMORY LEAKS, propKey and tbrCloseType..then we used only value from cache and call
                //propValue.Get(tr); or propKey.Get(tr);


                //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!  probably works faster http://fasterflect.codeplex.com   //but this one generates amazing results, only needs cach for alread known data structures
                //GETTING KEYS AND VALUES

                STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor propExists =
                    new STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor(tbrCloseType, "Exists");


                var tbrKeyExists = propExists.Get(tr);

                if (!(bool)tbrKeyExists)
                {
                    Console.WriteLine("NO RESULT");
                    return;             //NO RESULT FOUND IN DB //WE CAN SEND RESULT VALUE VIA WIRES
                }
                            

                STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor propKey =
                    new STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor(tbrCloseType, "Key");

                STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor propValue =
                    new STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor(tbrCloseType, "Value");

                //object ttt;           //takes 46 ms http://fasterflect.codeplex.com says about 21 ms (2MLN get property) of cached structures.
                //System.Diagnostics.Stopwatch sw = new Stopwatch();
                //sw.Start();
                //for (int i = 0; i <= 2000000; i++)
                //{
                //    ttt = propValue.Get(tr);
                //}
                //sw.Stop();
                //Console.WriteLine(sw.ElapsedMilliseconds);

                var tbrValue = propValue.Get(tr);
                var tbrKey = propKey.Get(tr);


                //System.Reflection.PropertyInfo tbrKeyExistsProperty = tbrCloseType.GetProperty("Exists");           //MUST BE UNDER FAST REFLECT


                ////////////////////////////works 738 ms
                //////////////////////////var q = Enumerable.Range(1, 1000000).Select<int, object>((r, v) =>
                //////////////////////////    {
                //////////////////////////        return tbrKeyExistsProperty.GetValue(tr, null);
                //////////////////////////    });

                //////////////////////////System.Diagnostics.Stopwatch sw = new Stopwatch();
                //////////////////////////sw.Start();
                //////////////////////////foreach (var rrr in q)
                //////////////////////////{

                //////////////////////////}
                //////////////////////////sw.Stop();
                //////////////////////////Console.WriteLine(sw.ElapsedMilliseconds);
                

                //////////////////works 69 ms
                ////////////////STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor propacc =
                ////////////////    new STSdb.MTL.Utils.Reflection.FastDynamicPropertyAccessor.PropertyAccessor(tbrCloseType, "Exists");

                //////////////////object ttt = propacc.Get(tr);

                ////////////////var q = Enumerable.Range(1, 1000000).Select<int, object>((r, v) =>
                ////////////////    {
                ////////////////        return propacc.Get(tr);
                ////////////////    });

                ////////////////System.Diagnostics.Stopwatch sw = new Stopwatch();
                ////////////////sw.Start();
                ////////////////foreach (var rrr in q)
                ////////////////{

                ////////////////}
                ////////////////sw.Stop();
                ////////////////Console.WriteLine(sw.ElapsedMilliseconds);



                //var tbrKeyExists = tbrKeyExistsProperty.GetValue(tr, null);

                //if (!(bool)tbrKeyExists)
                //{
                //    Console.WriteLine("NO RESULT");
                //    return;             //NO RESULT FOUND IN DB //WE CAN SEND RESULT VALUE VIA WIRES
                //}


                //System.Reflection.PropertyInfo tbrValueProperty = tbrCloseType.GetProperty("Value");            //MUST BE UNDER FAST REFLECT
                //var tbrValue = tbrValueProperty.GetValue(tr, null);

                ////or var tbrValue = tbrCloseType.GetProperty("Value").GetValue(tr, null);

                //System.Reflection.PropertyInfo tbrKeyProperty = tbrCloseType.GetProperty("Key");                //MUST BE UNDER FAST REFLECT
                //var tbrKey = tbrKeyProperty.GetValue(tr, null);

                //SERIALIZING VALUE TO STRING

                string serializedValue1 = "NULL"; //MEANS DEFAULT NULL VALUE
                if (tbrValue != null)
                {
                    serializedValue1 = SerializeXml(tbrValue);
                }
          

                

                //WE CAN SEND RESULT VALUE VIA WIRES

               // Console.WriteLine("K:{0}; V:{1}", tbrKey, serializedValue1);
            }
        }

        private string SerializeXml(object objectForSerialization)
        {
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(objectForSerialization.GetType());

            string r = String.Empty;

            using (System.IO.StringWriter wr = new System.IO.StringWriter())
            {
                xs.Serialize(wr, objectForSerialization);
                r = wr.GetStringBuilder().ToString();
                wr.Close();
            }

            return r;
        }
       

        private void DoTypeConversion()
        {
            if (_sts_engine == null)
                _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);


            //Type type = typeof(STS_wpf_tester.XCar);

            //this.insertCar();
            //this.SelectCar();
            //Type type1 = Type.GetType("STS_wpf_tester.XCar");

            this.SelectForwardCar();

           
        }



        #endregion




        #region "Multi Instances Transaction"

        
        STSdb.MTL.STSdbMTLengine dtDb = null;
        STSdb.MTL.STSdbMTLengine e1 = null;
        STSdb.MTL.STSdbMTLengine e2 = null;
        string dtDbPath = @"D:\temp\STS\dtDb.stsdb";
        string e1dbPath = @"D:\temp\STS\e1.stsdb";
        string e2dbPath = @"D:\temp\STS\e2.stsdb";


        private void StartMIT()
        {
            if (dtDb == null)
            {                
                dtDb = STSdb.MTL.DistributedTransactionCoordinator.CreateDistributedTransactionsDb(dtDbPath);
            }

            if(e1 == null)
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);

            if (e2 == null)
                e2 = new STSdb.MTL.STSdbMTLengine(e2dbPath);

            ////INSERTING INTO 2 DBs
            //using (STSdb.MTL.Transaction tran1 = e1.GetTransaction())
            //{
            //    using (STSdb.MTL.Transaction tran2 = e2.GetTransaction())
            //    {

            //        tran1.Insert<int, string>("tbl1", 1, "one");
            //        tran2.Insert<int, string>("tbl1", 2, "two");                                       

            //        STSdb.MTL.DistributedTransactionCoordinator.CommitDistributedTransactions(tran1, tran2);

            //    }
            //}


            //Get Transaction
            using (STSdb.MTL.Transaction tran = dtDb.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<long, byte>("@sys_dstTranHeader", STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
                }
            }



            //Checking info from 2 db's
            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
                }
            }

            Console.WriteLine("-----------");

            using (STSdb.MTL.Transaction tran = e2.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
                }
            }


            
            //using (STSdb.MTL.Transaction t2 = e2.GetTransaction())
            //{
            //    foreach (var tr in t2.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}

            //using (STSdb.MTL.Transaction t2 = e2.GetTransaction())
            //{
            //    foreach (var tr in t2.SelectForward<int, string>("snapshot", STSdb.MTL.eSelectMode.READ))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}


            //using (STSdb.MTL.Transaction t1 = e1.GetTransaction())
            //{
            //    using (STSdb.MTL.Transaction t2 = e2.GetTransaction())
            //    {

            //        //t2.Select<int, string>("t1", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
            //        //t1.Select<int, string>("t1", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
            //        //t1.Select<int, string>("t2", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
            //        //t1.Select<int, string>("t3", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
            //        //t1.Select<int, string>("t4", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
            //        //t1.Select<int, string>("t5", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);

            //        t2.Insert<int, string>("tbl1", 1, "one");
            //        t2.Insert<int, string>("tbl1", 2, "two");

            //        t2.Commit();

            //        //STSdb.MTL.DistributedTransactionCoordinator.CommitDistributedTransactions(t1, t2);
            //        //STSdb.MTL.Engines.CommitDistributedTransactions
            //    }
            //}

            //using (STSdb.MTL.Transaction t2 = e2.GetTransaction())
            //{
            //    t2.Select<int, string>("tbl1", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
            //    STSdb.MTL.DistributedTransactionCoordinator.CommitDistributedTransactions(t2);
            //}
        }

        private void TestSnapshots()
        {

            if (e1 == null)
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);

            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine("T: {0}; ", tn);
            //}


            //using (var tran = e1.GetTransaction())
            //{
            //    tran.DeleteTable("tbl1_snapshot");
            //}

            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine("T: {0}; ", tn);
            //}

            //return;


            //using (var tran = e1.GetTransaction())
            //{
            //    tran.Insert<int, string>("tbl1", 1, "as1");
            //    tran.Insert<int, string>("tbl1", 2, "as2");
            //    tran.Commit();
            //}

            //using (var tran = e1.GetTransaction())
            //{
            //    tran.CreateTableSnapshot<int, string>("tbl1", "tbl1_snapshot");
            //}


            //using (var tran = e1.GetTransaction())
            //{
            //    Console.WriteLine("----------   CONTENT OF SNAPSHOT TABLE ------------");

            //    foreach (var tr in tran.SelectForward<int, string>("tbl1_snapshot", STSdb.MTL.eSelectMode.READ))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }

            //    tran.Insert<int, string>("tbl1", 3, "as3");
            //    tran.Commit();
            //}

            //using (var tran = e1.GetTransaction())
            //{
            //    tran.RestoreTableFromSnapshot<int, string>("tbl1", "tbl1_snapshot");
            //}

            //using (var tran = e1.GetTransaction())
            //{
            //    Console.WriteLine("----------   CONTENT OF RESTORED TBL1 FROM SNAPSHOT ------------");
            //    foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);             
            //    }
            //}


            //using (StorageEngine engine = StorageEngine.FromFile(@"D:\temp\STS\e1.stsdb"))
            //{
            //    //create the table
            //    var table = engine.Scheme.CreateOrOpenXTable<int, string>(new Locator("t1"));
            //    //commit changes to the scheme
            //    engine.Scheme.Commit();

            //    //add records to the table
            //    for (int i = 0; i < 10; i++)
            //    {
            //        table[i] = i.ToString();
            //    }

            //    //commit table changes
            //    table.Commit();

            //    var snapshot = table.Snapshot();

            //    var nl = new Locator("snapshot");
            //    engine.Scheme.Register(new Locator("snapshot"), snapshot);
            //    engine.Scheme.Commit();
            //    snapshot.Commit();

            //    table[11] = "11";
            //    table.Commit();

            //    var tsnap = engine.Scheme.OpenXTable<int, string>(new Locator("snapshot"));
            //    foreach (var tr in tsnap.Forward(1, 11))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Record);
            //    }

            //    Console.WriteLine("--");

            //    foreach (var tr in table.Forward(1, 11))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Record);
            //    }

            //}
        }


        private void TestSchemas()
        {
            using (StorageEngine engine = StorageEngine.FromFile(@"D:\temp\STS\e1.stsdb"))
            {
                STSdb.Data.Row<STSdb.Data.Locator, STSdb.Data.SchemeRecord> sr = null;

                //bool ist = engine.Scheme.Exists(new Locator("snapshot1"));

                var rrr = engine.Scheme.Select(r => r.Key.Items[0] == "snapshot").FirstOrDefault();

                var tz = engine.Scheme.Size;
                
                
                foreach (var schemeRow in engine.Scheme.Select(r=>r.Key))
                {
                    //sr = schemeRow;
                }
            }


            //if (e1 == null)
            //    e1 = new STSdb.MTL.STSdbMTLengine(@"D:\temp\STS\e1.stsdb");

            //bool e = e1.Scheme.IF_TableExists("snapshot1");


        }

               
        private void TestCreateDbFromMultipleFiles()
        {

            if (e1 == null)
            {
                //e1 = new STSdb.MTL.STSdbMTLengine(@"D:\temp\STS\", "mydb", "db", 2 * 1024 * 1024);
                //e1 = new STSdb.MTL.STSdbMTLengine(@"D:\temp\STS\", "mydb", "db", 1 * 1024 * 1024);
                e1 = new STSdb.MTL.STSdbMTLengine(@"D:\temp\STS\", "mydb", "db", 1 * 1024 * 1024);
            }


            //using (var tran = e1.GetTransaction())
            //{
            //    foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ).Take(10))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}

            //using (var tran = e1.GetTransaction())
            //{
            //    foreach (var tr in tran.SelectForward<int, string>("tbl2", STSdb.MTL.eSelectMode.READ).Take(10))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}


            //using (var tran = e1.GetTransaction())
            //{
            //    foreach (var tr in tran.SelectForward<int, string>("tbl3", STSdb.MTL.eSelectMode.READ).Take(10))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}

            using (var tran = e1.GetTransaction())
            {
                for (int i = 0; i < 1000000; i++)
                {
                    tran.Insert<int, string>("tbl3", i, "sda" + i.ToString());
                }

                tran.Commit();
            }

            //using (var tran = e1.GetTransaction())
            //{
            //    foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ).Take(10))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}

            return;


            //if (e1 == null)
            //{
            //    volumeChain = new STSdb.Volumes.VolumeChain();
            //    volumeChain.QuotaExceed += new STSdb.Volumes.VolumeChain.QuotaExceedDelegate(chain_QuotaExceed);

            //    foreach (string fileName in Directory.GetFiles(@"D:\temp\STS", "test.*.stsdb"))
            //    {
            //        volumeChain.Add(new STSdb.Volumes.Volume(fileName));
            //    }
                
            //    e1 = new STSdb.MTL.STSdbMTLengine(volumeChain);
            //}

           

            //using (var tran = e1.GetTransaction())
            //{
            //    for (int i = 0; i < 1000000; i++)
            //    {
            //        tran.Insert<int, string>("tbl1", i, "sda" + i.ToString());
            //    }

            //    tran.Commit();
            //}


            //using (var tran = e1.GetTransaction())
            //{
            //    foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
            //    }
            //}
        }


        private void TestRemoteCommands()
        {
            //creating db

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
                STSdb.MTL.Engines.AddEngine("testEngine", e1);
            }

            ////inserting some values
            //using(var tran = e1.GetTransaction())
            //{
            //    tran.Insert<int, string>("tbl1", 1, "a1");
            //    tran.Insert<int, string>("tbl1", 2, "a2");
            //    tran.Commit();
            //}

            //Fetching data SELECT
            string res = String.Empty;

            ////public string Select(string tableName, Type keyType, Type valueType, string selectMode, string key)

            //res = STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "testEngine",
            //    Command = "select",
            //    Parameters = { "tbl1", "System.Int32","System.String","READ","1" }
            //});

            ////tran.NonGenerics.SelectForward("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ", 10);

            //res = STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "testEngine",
            //    Command = "SelectForward",
            //    Parameters = { "tbl1", "System.Int32", "System.String", "READ", "2" }
            //});

            //res = STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "testEngine",
            //    Command = "GETALLTABLESNAMES",
            //    Parameters = {  }
            //});

            ////tran.NonGenerics.Count("cars", Type.GetType("System.Int32"), Type.GetType("STS_wpf_tester.XCar"), "READ");

            //res = STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "testEngine",
            //    Command = "Count",
            //    Parameters = { "tbl1", "System.Int32", "System.String", "READ" }
            //});


            //res = STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "testEngine",
            //    Command = "MaxRow",
            //    Parameters = { "tbl1", "System.Int32", "System.String", "READ" }
            //});


            //res = STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "testEngine",
            //    Command = "MinRow",
            //    Parameters = { "tbl1", "System.Int32", "System.String", "READ" }
            //});


            //MULTIPLE COMMANDS

            res = STSdb.MTL.Engines._RMQC.ExecuteCommands(
                new List<STSdb.MTL.RemoteCommand>
                    {
                        new STSdb.MTL.RemoteCommand()
                        {
                            EngineName = "testEngine",
                            Command = "MaxRow",
                            Parameters = { "tbl1", "System.Int32", "System.String", "READ" }
                        },
                        new STSdb.MTL.RemoteCommand()
                        {
                            EngineName = "testEngine",
                            Command = "MinRow",
                            Parameters = { "tbl1", "System.Int32", "System.String", "READ" }
                        }
                }
            );


            Console.WriteLine(res);

        }


        #endregion


        #region "FileSizeTest"

        public void CreateEmptyTables(int tableCount)
        {
           

            Stopwatch sw = new Stopwatch();
            sw.Start();

            using (StorageEngine engine = StorageEngine.FromFile(e1dbPath))
            {
                STSdb.Files.RawFile file = engine.FileSystem.CreateFile();

                for (int i = 0; i < tableCount; i++)
                {
                    Locator locator = new Locator("table", i.ToString());

                    //create and register the table
                    XTable<int, string> table;
                    lock (file.SyncRoot)
                        table = new XTable<int, string>(file, file.Length);
                    engine.Scheme.Register<int, string>(locator, table);
                    //engine.Scheme.Commit();
                }
                engine.Scheme.Commit();
                
            }

            sw.Stop();

            FileInfo fi = new FileInfo(e1dbPath);
            Console.WriteLine("Insert {0} tables", tableCount);
            Console.WriteLine("Insert time: {0} tables/sec", 1000.0 * tableCount / sw.ElapsedMilliseconds);
            Console.WriteLine("{0} {1} mb, {2} bytes per table", fi.Name, fi.Length / (1024 * 1024.0), fi.Length / (double)tableCount);
        }

        private void TestFileSizes()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);                
                //e1 = new STSdb.MTL.STSdbMTLengine(e2dbPath);                
            }

            using (var tran = e1.GetTransaction())
            {
                System.Diagnostics.Stopwatch sw = new Stopwatch();
                sw.Start();
                for (int i = 1; i <= 1000; i++)
                {
                    tran.Count<int, string>("table" + i.ToString());
                }
                sw.Stop();
                Console.WriteLine("MS: {0}; Ticks: {1}", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                
            }
        }

        //[Serializable]
        //public class Xvalue
        //{
        //    public Xvalue()
        //    {
        //        Intt = 0;
        //        Longg = 0;
        //        Strings = new List<string>();
        //    }

        //    public int Intt { get; set; }
        //    public long Longg { get; set; }

        //    public List<string> Strings { get; set; }
        //}

        #endregion


        #region "test asynchro write and read"

        private void test_startAO()
        {
            System.IO.File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
                //e1 = new STSdb.MTL.STSdbMTLengine(e2dbPath);     

                e1.Scheme.SetTableProperties<int, byte>("t1", new STSdb.MTL.TableProperties<int, byte>()
                    {
                        BlockCapacity = 10
                    });
            }

            _testMgr = new STSdbMTL_TestManager(e1);

            Action writeT1 = () =>
            {
                string table = "t1";
                int cnt = 1000000;
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    Console.WriteLine("WRITE_"+table+"_STARTED");
                    System.Diagnostics.Stopwatch sw = new Stopwatch();
                    sw.Start();

                    for (int i = 0; i <= cnt; i++)
                    {
                        tran.Insert<int, byte>(table, i, 1);
                    }
                    tran.Commit();

                    sw.Stop();
                    Console.WriteLine("WRITE_"+table+"_FINISHED MS: {0}; Ticks: {1}", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                }
            };
           
            //this._testMgr.StartActionInThread(writeT1);

            Action writeT2 = () =>
            {
                string table = "t2";
                int cnt = 10000;
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    Console.WriteLine("WRITE_" + table + "_STARTED");
                    System.Diagnostics.Stopwatch sw = new Stopwatch();
                    sw.Start();

                    for (int i = 0; i <= cnt; i++)
                    {
                        tran.Insert<int, byte>(table, i, 1);
                    }
                    tran.Commit();

                    sw.Stop();
                    Console.WriteLine("WRITE_" + table + "_FINISHED MS: {0}; Ticks: {1}", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                }
            };

            //this._testMgr.StartActionInThread(writeT2);



            Action writeT3 = () =>
            {
                string table = "t3";
                int cnt = 10000;
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    Console.WriteLine("WRITE_" + table + "_STARTED");
                    System.Diagnostics.Stopwatch sw = new Stopwatch();
                    sw.Start();

                    for (int i = 0; i <= cnt; i++)
                    {
                        tran.Insert<int, byte>(table, i, 1);
                    }
                    tran.Commit();

                    sw.Stop();
                    Console.WriteLine("WRITE_" + table + "_FINISHED MS: {0}; Ticks: {1}", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                }
            };

            //this._testMgr.StartActionInThread(writeT3);




            Action writeT1asBlocks = () =>
            {
                string table = "t1";
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    Console.WriteLine("WRITE_" + table + "_STARTED");
                    System.Diagnostics.Stopwatch sw = new Stopwatch();
                    sw.Start();

                    for (int j = 0; j < 1000; j++)
                    {
                        for (int i = 1; i <= 1000; i++)
                        {
                            tran.Insert<int, byte>(table, j * 1000 + i, 1);
                        }
                        tran.Commit();
                    }

                    sw.Stop();
                    Console.WriteLine("WRITE_" + table + "_FINISHED MS: {0}; Ticks: {1}", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                }
            };

            //this._testMgr.StartActionInThread(writeT1asBlocks);


            Action readT1 = () =>
            {
                string table = "t1";
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    Console.WriteLine("READ_" + table + "_STARTED");

                    for (int j = 0; j < 50000; j++)
                    {
                        Console.WriteLine("R" + j.ToString());

                        foreach (var tr in tran.SelectForward<int, byte>(table, STSdb.MTL.eSelectMode.READ).Take(5))
                        {
                            Console.WriteLine("K: {0}; ", tr.Key);
                        }
                    }

                }
            };

           // this._testMgr.StartActionInThread(readT1);

        }

        #endregion

        #region "Testing Snapshots 2"

        private void CreateMultipleSnapshots()
        {
            if (e1 == null)
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);

            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine("T: {0}; ", tn);
            //}


            //using (var tran = e1.GetTransaction())
            //{
            //    tran.DeleteTable("tbl1_snapshot");
            //}

            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine("T: {0}; ", tn);
            //}

            //return;


            using (var tran = e1.GetTransaction())
            {
                tran.Insert<int, string>("tbl1", 1, "as1");
                tran.Insert<int, string>("tbl1", 2, "as2");
                tran.Commit();
            }

            //using (var tran = e1.GetTransaction())
            //{
            //    for (int i = 0; i < 1000; i++)
            //    {
            //        tran.CreateTableSnapshot<int, string>("tbl1", "tbl" + i.ToString() + "_snapshot");
            //    }
            //}

            return;

            using (var tran = e1.GetTransaction())
            {
                Console.WriteLine("----------   CONTENT OF SNAPSHOT TABLE ------------");

                foreach (var tr in tran.SelectForward<int, string>("tbl1_snapshot", STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
                }

                tran.Insert<int, string>("tbl1", 3, "as3");
                tran.Commit();
            }

            //using (var tran = e1.GetTransaction())
            //{
            //    tran.RestoreTableFromSnapshot<int, string>("tbl1", "tbl1_snapshot");
            //}

            using (var tran = e1.GetTransaction())
            {
                Console.WriteLine("----------   CONTENT OF RESTORED TBL1 FROM SNAPSHOT ------------");
                foreach (var tr in tran.SelectForward<int, string>("tbl1", STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
                }
            }
        }


        #endregion

        #region "Testing Transaction Log"

        private void TestTransactionLog()
        {
            //STSdb.MTL.STSdbMTLengine e1 = null;
            //STSdb.MTL.STSdbMTLengine e2 = null;
            //string dtDbPath = @"D:\temp\STS\dtDb.stsdb";
            //string e1dbPath = @"D:\temp\STS\e1.stsdb";

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
                e1.TransactionLog = new STSdb.MTL.EngineTransactionsLog(
                    new STSdb.MTL.EngineTransactionsLogSetup()
                     {
                         LogFilesFolderName = @"D:\temp\STS",
                         LogFileBaseName = "log.txt"
                     }
                    );
            }

            

            using (var tran = e1.GetTransaction())
            {
                tran.Insert<int, int>("t1", 2, 12);
                tran.Commit();
            }
        }

        #endregion


        public class Settings
        {
            public Settings() { }

            public long FBSI { get; set; }
        }

        private void TestValueAsObject()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            List<Settings> sets = new List<Settings>()
            {
                 new Settings(){ FBSI=1},
                 new Settings(){ FBSI=2},
                 new Settings(){ FBSI=3},
            };

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                tran.Insert<long, object>("Firma/Settings", 1, sets.SerializeXml());
                tran.Commit();
            }

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                STSdb.MTL.TableRow<long, object> s = tran.Select<long, object>("Firma/Settings", STSdb.MTL.eSelectMode.READ, 1);
                if (s.Value != null)
                {
                   // Console.WriteLine("K: {0}; V: {1}", s.Key, s.Value.ToString().DeserializeXml<Settings>().FBSI.ToString());
                }
                else
                {
                    Console.WriteLine("Val is null");
                }
            }


            /////////////////////////////////

            //Settings sett = new Settings();
            //sett.FBSI = 20;

            //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    tran.Insert<long, object>("Firma/Settings", 1, sett.SerializeXml());
            //    tran.Commit();
            //}


            //for (int i = 0; i < 200; i++)
            //{
            //    using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //    {
            //        STSdb.MTL.TableRow<long, object> s = tran.Select<long, object>("Firma/Settings", STSdb.MTL.eSelectMode.READ, 2);
            //        if (s.Value != null)
            //        {
            //            Console.WriteLine("K: {0}; V: {1}", s.Key, s.Value.ToString().DeserializeXml<Settings>().FBSI.ToString());
            //        }
            //        else
            //        {
            //            Console.WriteLine("Val is null");
            //        }
            //    }
            //}          



        }

      
        private void TestGoto()
        {
           
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                tran.Insert<long, string>("Firma/Settings", 1, "");
                tran.Commit();

                goto l1;
            }

        l1: ;
        }


        private void TestExists()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }


            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {

                //for (int i = 0; i < 1000000; i++)
                //{
                //    tran.Insert<int, string>("d8", i, i.ToString());          
                //}

                //tran.Commit();

                System.Diagnostics.Stopwatch sw = new Stopwatch();

                sw.Start();

                //1303 ms
                //foreach (var tr in tran.SelectForward<int, string>("d8", STSdb.MTL.eSelectMode.READ).Skip(500000).Take(10))
                //{
                //    Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                //}

                //1 ms
                foreach (var tr in tran.SelectForward<int, string>("d8", STSdb.MTL.eSelectMode.READ,500000).Take(5000000))
                {
                   // Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                }

                sw.Stop();
                Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds,sw.ElapsedTicks);

                    

                //tran.RegisterWriteOrSynchroReadTables("d8");

                //tran.Insert<long, byte>("d8", 1, 1);
                //tran.Commit();

                //var tr = tran.Select<long, string>("d8", STSdb.MTL.eSelectMode.READ, 1);

                //if (!tr.Exists)
                //{
                //    tr.Value = "kuku";
                //    tran.Commit();
                //}

            }
        }



        #region "Testing Small Transactions"

        [Serializable]
        public class D8_V2_DriverRelatedData
        {
            public D8_V2_DriverRelatedData()
            {
                HexMsg = String.Empty;
                DvTp = "D8_V2";
            }

            public long utcInsertDtTicks { get; set; }
            public long utcPackageDtTicks { get; set; }

            public string DriverCard { get; set; }
            public string Activity { get; set; }

            public long TroId { get; set; }

            public string D8MessageId { get; set; }

            public string HexMsg { get; set; }

            /// <summary>
            /// Device Type D8_1, D8_V2
            /// </summary>
            public string DvTp { get; set; }
        }

        private void TestingSmallTransactionsV1()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            long initDbSize = (new FileInfo(e1dbPath)).Length;

            Console.WriteLine("Initial DB Size: {0} bytes", initDbSize);
            int quantityOfTransactions = 1000;
            //Block Capacity = 1024

            long initKey = DateTime.Now.Ticks;

            System.Diagnostics.Stopwatch sw=new Stopwatch();

            sw.Start();

            //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    var tr = tran.Select<long, D8_V2_DriverRelatedData>("D8_V2_DRD/323", STSdb.MTL.eSelectMode.READ, 1);
            //}

            for (int i = 0; i < quantityOfTransactions; i++)
            {
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    initKey++;
                    tran.Insert<long, D8_V2_DriverRelatedData>("D8_V2_DRD/323", initKey, new D8_V2_DriverRelatedData()
                    {
                        utcInsertDtTicks = initKey,
                        utcPackageDtTicks = initKey,
                        DriverCard = "DF00004962852000",
                        Activity = "DF00004962852000",
                        TroId = 323,
                        D8MessageId = "743",
                        HexMsg = "0x07 0x20 0x44 0x46 0x30 0x30 0x30 0x30 0x34 0x39 0x36 0x32 0x38 0x35 0x32 0x30 0x30 0x30 0x03",
                        DvTp = "D8_V2"
                    });

                    tran.Commit();
                }

                //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                //{
                //    var tr = tran.Select<long, D8_V2_DriverRelatedData>("D8_V2_DRD/323", STSdb.MTL.eSelectMode.READ, 1);
                //}
            }

            //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    var tr = tran.Select<long, D8_V2_DriverRelatedData>("D8_V2_DRD/323", STSdb.MTL.eSelectMode.READ, 1);
            //}

            sw.Stop();
            Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

            long finalDbSize = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("Final DB Size: {0} bytes", finalDbSize - initDbSize);

            //TERRIBLE BLOCK CAPACITY = 1024
            //Initial DB Size: 657220 bytes
            //Took: 37800 ms; 103286937 ticks
            //Final DB Size: 286453550 bytes

            //BLOCK CAPACITY = 1
            //Initial DB Size: 657220 bytes
            //Took: 27247 ms; 74451969 ticks
            //Final DB Size: 69995017 bytes
        }


        private void TestingSmallTransactionsV2()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            long initDbSize = (new FileInfo(e1dbPath)).Length;

            Console.WriteLine("Initial DB Size: {0} bytes", initDbSize);
            int quantityOfTransactions = 1000;
            //Block Capacity = 1024

            long initKey = DateTime.Now.Ticks;

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Start();

            D8_V2_DriverRelatedData drd = new D8_V2_DriverRelatedData()
            {
                utcInsertDtTicks = initKey,
                utcPackageDtTicks = initKey,
                DriverCard = "DF00004962852000",
                Activity = "DF00004962852000",
                TroId = 323,
                D8MessageId = "743",
                HexMsg = "0x07 0x20 0x44 0x46 0x30 0x30 0x30 0x30 0x34 0x39 0x36 0x32 0x38 0x35 0x32 0x30 0x30 0x30 0x03",
                DvTp = "D8_V2"
            };


            string sr = drd.SerializeXml(); //592 bytes
                        

            for (int i = 0; i < quantityOfTransactions; i++)
            {
                //D8_V2_DriverRelatedData drd = new D8_V2_DriverRelatedData()
                //{
                //    utcInsertDtTicks = initKey,
                //    utcPackageDtTicks = initKey,
                //    DriverCard = "DF00004962852000",
                //    Activity = "DF00004962852000",
                //    TroId = 323,
                //    D8MessageId = "743",
                //    HexMsg = "0x07 0x20 0x44 0x46 0x30 0x30 0x30 0x30 0x34 0x39 0x36 0x32 0x38 0x35 0x32 0x30 0x30 0x30 0x03",
                //    DvTp = "D8_V2"
                //};


                //string sr = drd.SerializeXml(); //592 bytes

                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    initKey++;
                    tran.Insert<long, string>("D8_V2_DRD/323", initKey, sr);

                    tran.Commit();
                }
            }

            sw.Stop();
            Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

            long finalDbSize = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("Final DB Size: {0} bytes", finalDbSize - initDbSize);

            //BLOCK CAPACITY = 1, data is tored as serialized value (1000 vals)
            //Initial DB Size: 657220 bytes
            //Took: 24706 ms; 67509730 ticks
            //Final DB Size: 9174471 bytes

            //BLOCK CAPACITY = 1  (1000 vals)
            //Initial DB Size: 657220 bytes
            //Took: 23683 ms; 64712856 ticks
            //Final DB Size: 8912327 bytes

            //BLOCK CAPACITY = 1024  (1000 vals)
            //Initial DB Size: 657220 bytes
            //Took: 29064 ms; 79418304 ticks
            //Final DB Size: 30387189 bytes

            //BLOCK CAPACITY = 1  (10000 vals)
            //Initial DB Size: 657220 bytes           
            //Took: 587554 ms; 1605464287 ticks
            //Final DB Size: 92351452 bytes

            //BLOCK CAPACITY = 1  (1000 vals after 10000)
            //Initial DB Size: 93008672 bytes
            //Took: 40800 ms; 111484311 ticks
            //Final DB Size: 8412561 bytes
        }

        //TEST


        private void FetchDRDData()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Start();

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<long, string>("D8_V2_DRD/323",STSdb.MTL.eSelectMode.READ))
                {
                }
            }

            sw.Stop();
            Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);
        }


        private void TestingSmallTransactionsV3()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            long initDbSize = (new FileInfo(e1dbPath)).Length;

            Console.WriteLine("Initial DB Size: {0} bytes", initDbSize);
            int quantityOfTransactions = 10000;
            //Block Capacity = 1024

            long initKey = DateTime.Now.Ticks;

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Start();

            D8_V2_DriverRelatedData drd = new D8_V2_DriverRelatedData()
            {
                utcInsertDtTicks = initKey,
                utcPackageDtTicks = initKey,
                DriverCard = "DF00004962852000",
                Activity = "DF00004962852000",
                TroId = 323,
                D8MessageId = "743",
                HexMsg = "0x07 0x20 0x44 0x46 0x30 0x30 0x30 0x30 0x34 0x39 0x36 0x32 0x38 0x35 0x32 0x30 0x30 0x30 0x03",
                DvTp = "D8_V2"
            };


            string sr = drd.SerializeXml(); //592 bytes




            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                for (int i = 0; i < quantityOfTransactions; i++)
                {
                    initKey++;
                    tran.Insert<long, string>("D8_V2_DRD/323", initKey, sr);                    
                }

                tran.Commit();
            }

            sw.Stop();
            Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

            long finalDbSize = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("Final DB Size: {0} bytes", finalDbSize - initDbSize);

          //Initial DB Size: 657220 bytes
          //Took: 543 ms; 1485347 ticks
          //Final DB Size: 625233 bytes
        }


        private void TestingSmallTransactionsV4()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            long initDbSize = (new FileInfo(e1dbPath)).Length;

            Console.WriteLine("Initial DB Size: {0} bytes", initDbSize);
            int quantityOfTransactions = 10000;
            //Block Capacity = 1024

            long initKey = DateTime.Now.Ticks;

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Start();

            D8_V2_DriverRelatedData drd = new D8_V2_DriverRelatedData()
            {
                utcInsertDtTicks = initKey,
                utcPackageDtTicks = initKey,
                DriverCard = "DF00004962852000",
                Activity = "DF00004962852000",
                TroId = 323,
                D8MessageId = "743",
                HexMsg = "0x07 0x20 0x44 0x46 0x30 0x30 0x30 0x30 0x34 0x39 0x36 0x32 0x38 0x35 0x32 0x30 0x30 0x30 0x03",
                DvTp = "D8_V2"
            };


            string sr = drd.SerializeXml(); //592 bytes




            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                for (int i = 0; i < quantityOfTransactions; i++)
                {
                    initKey++;
                    tran.Insert<long, D8_V2_DriverRelatedData>("D8_V2_DRD/323", initKey, drd);
                }

                tran.Commit();
            }

            sw.Stop();
            Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

            long finalDbSize = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("Final DB Size: {0} bytes", finalDbSize - initDbSize);

            //Initial DB Size: 657220 bytes
            //Took: 627 ms; 1715318 ticks
            //Final DB Size: 5734529 bytes
        }


        private void TestingSmallTransactionsV5()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            long initDbSize = (new FileInfo(e1dbPath)).Length;

            Console.WriteLine("/*");
            Console.WriteLine("Initial DB Size: {0} bytes", initDbSize);
            int quantityOfTransactions = 100;
            //Block Capacity = 1024

            long initKey = DateTime.Now.Ticks;

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Start();

            D8_V2_DriverRelatedData drd = new D8_V2_DriverRelatedData()
            {
                utcInsertDtTicks = initKey,
                utcPackageDtTicks = initKey,
                DriverCard = "DF00004962852000",
                Activity = "DF00004962852000",
                TroId = 323,
                D8MessageId = "743",
                HexMsg = "0x07 0x20 0x44 0x46 0x30 0x30 0x30 0x30 0x34 0x39 0x36 0x32 0x38 0x35 0x32 0x30 0x30 0x30 0x03",
                DvTp = "D8_V2"
            };


            string sr = drd.SerializeXml(); //592 bytes




            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                for (int i = 0; i < quantityOfTransactions; i++)
                {
                    initKey++;
                    //tran.Insert<long, D8_V2_DriverRelatedData>("D8_V2_DRD/323", initKey, drd);
                    tran.Insert<long, string>("D8_V2_DRD/323", initKey, sr);

                    tran.Commit();
                }

               // tran.Commit();
            }

            sw.Stop();
            Console.WriteLine("Took: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

            
            long finalDbSize = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("Total DB Size: {0} bytes", finalDbSize);
            Console.WriteLine("Final DB Size: {0} bytes", finalDbSize - initDbSize);
            Console.WriteLine("Record size: {0} bytes", (finalDbSize - initDbSize) / quantityOfTransactions);
            Console.WriteLine("*/");
                      
            /* 100 commit in the end  object as value
            Initial DB Size: 657220 bytes
            Took: 429 ms; 1172249 ticks
            Total DB Size: 845977 bytes
            Final DB Size: 188757 bytes
            Record size: 1887 bytes
            */

            /* 1000 commit in the end  object as value
            Initial DB Size: 845977 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'pwwnaacm'
            Took: 458 ms; 1252059 ticks
            Total DB Size: 1406494 bytes
            Final DB Size: 560517 bytes
            Record size: 560 bytes
            */

            /* 10000 commit in the end  object as value
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'r4jp9d2c'
            Took: 630 ms; 1724151 ticks
            Total DB Size: 6391795 bytes
            Final DB Size: 5734575 bytes
            Record size: 573 bytes
            */

            /* 100 commit in the middle  object as value
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'aukrba-a'
            Took: 2564 ms; 7007287 ticks
            Total DB Size: 2797358 bytes
            Final DB Size: 2140138 bytes
            Record size: 21401 bytes
            */

            /* 1000 commit in the middle object as value
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'm_0-etqq'
            Took: 25929 ms; 70851589 ticks
            Total DB Size: 68486411 bytes
            Final DB Size: 67829191 bytes
            Record size: 67829 bytes
            */

            /* 2000 commit in the middle object as value
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded '3w5rd_qv'
            Took: 55551 ms; 151790431 ticks
            Total DB Size: 142171383 bytes
            Final DB Size: 141514163 bytes
            Record size: 70757 bytes
            */

            /* 3000 commit in the middle object as value
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded '9hqgy7ms'
            Took: 93544 ms; 255606505 ticks
            Total DB Size: 216324642 bytes
            Final DB Size: 215667422 bytes
            Record size: 71889 bytes
            */

            //-------- STRING

            /* 3000 commit in the middle object as STRING
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'cuv6wlsv'
            Took: 83320 ms; 227669948 ticks
            Total DB Size: 27539908 bytes
            Final DB Size: 26882688 bytes
            Record size: 8960 bytes
            */

            /* 2000 commit in the middle object as STRING
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'nwxle8r0'
            Took: 50082 ms; 136847718 ticks
            Total DB Size: 18395629 bytes
            Final DB Size: 17738409 bytes
            Record size: 8869 bytes
            */

            /* 1000 commit in the middle object as STRING
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'lds7qifl'
            Took: 23765 ms; 64937243 ticks
            Total DB Size: 9241867 bytes
            Final DB Size: 8584647 bytes
            Record size: 8584 bytes
            */

            /* 100 commit in the middle object as STRING
            Initial DB Size: 657220 bytes
            'STS_wpf_tester.vshost.exe' (Managed (v2.0.50727)): Loaded 'yv4mxmvl'
            Took: 2496 ms; 6821864 ticks
            Total DB Size: 1210483 bytes
            Final DB Size: 553263 bytes
            Record size: 5532 bytes
            */
        }
        #endregion


        #region "Testing Newly created Db File Size"

        private void TestEmptyTablesSize()
        {
            File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            int qTables = 20;

            System.Diagnostics.Stopwatch sw = new Stopwatch();
            sw.Start();
            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {

                for (int i = 0; i < qTables; i++)
                {
                    tran.Select<int, string>("tb" + i, STSdb.MTL.eSelectMode.READ, 1);
                    tran.Commit();
                }

                //tran.Commit();
            }

            sw.Stop();

            long fl = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("//DONE {0}; {1} ms; {2} bytes/table; {3} ms/table", fl, sw.ElapsedMilliseconds, fl / qTables, sw.ElapsedMilliseconds / qTables);

            e1.Dispose();

            //Commit outside
            //DONE 145512924; 13121 ms; 145512 bytes/table; 13 ms/table - byte
            //DONE 145491780; 13490 ms; 145491 bytes/table; 13 ms/table - int
            //DONE 145569131; 14490 ms; 145569 bytes/table; 14 ms/table - string

            //Commit inside
            //DONE 147338603; 44043 ms; 147338 bytes/table; 44 ms/table - string

            //All can be compressed to 111 Kb by 7zip
        }

        private void InsertRandomValues(int quantity,int byteValueSize,string tableName,bool deleteFile,bool commitAfter)
        {
            if(deleteFile)
                File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            Random rnd = new Random();
            int qRow = quantity;

            byte[] bt = new byte[byteValueSize];

            System.Diagnostics.Stopwatch sw = new Stopwatch();
            sw.Start();
            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {

                for (int i = 0; i < qRow; i++)
                {
                    rnd.NextBytes(bt);
                    tran.Insert<long, byte[]>(tableName, rnd.Next(Int32.MaxValue), bt);

                    if (!commitAfter)
                        tran.Commit();
                }

                if(commitAfter)
                    tran.Commit();

            }
            sw.Stop();

            long fl = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("//DONE: FileLen: {3} bytes; {0} ms; {1} bytes/row; {2} ms/row", sw.ElapsedMilliseconds, fl / qRow, sw.ElapsedMilliseconds / qRow,fl);

            //e1.Dispose();
            //e1 = null;
            //DONE: FileLen: 3867915 bytes; 27800 ms; 3867 bytes/row; 27 ms/row  Random byte[] commit after every row
        }

        /// <summary>
        /// Default -1
        /// </summary>
        /// <param name="quantityToInsert"></param>
        private void InsertSequentialValues(int quantityToInsert,string tableName)
        {
            //File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }



            //int qRow = 2000000;
            int qRow = 2000000;

            if (quantityToInsert != -1)
                qRow = quantityToInsert;

            long tm=0;

            System.Diagnostics.Stopwatch sw = new Stopwatch();
            sw.Start();
            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {

                for (int i = 0; i < qRow; i++)
                {
                    tm = DateTime.Now.Ticks;
                    tran.Insert<long, string>(tableName, tm, tm.ToString() + "sdf jsdlkfj lsdkjflskdjf erui fuirhkfjh ydlfk" + tm.ToString() + "jg vcm,bcm,xbdfukgh eruit whghfdkln,cmvbncv,.xmbnfkjdgh urie " + tm.ToString());                    
                }

                tran.Commit();
            }
            sw.Stop();

            long fl = (new FileInfo(e1dbPath)).Length;
            Console.WriteLine("//DONE InsertSequentialValues: FileLen: {3} bytes; Rows: {4}; {0} ms; {1} bytes/row; {2} ms/row", sw.ElapsedMilliseconds, fl / qRow, sw.ElapsedMilliseconds / qRow, fl, qRow);

            //e1.Dispose();
            //e1 = null;

            //DONE: FileLen: 3347010 bytes; Row: 2000000; 12656 ms; 1 bytes/row; 0 ms/row
            //DONE: FileLen: 4872882 bytes; Row: 2000000; 17712 ms; 2 bytes/row; 0 ms/row
            
        }

        private void CopyToNewTable()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            int qRow = 0;

            System.Diagnostics.Stopwatch sw = new Stopwatch();
            sw.Start();
            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<long, byte[]>("t1", STSdb.MTL.eSelectMode.READ_SYNCHRO))
                {
                    tran.Insert<long, byte[]>("t1_copy",tr.Key,tr.Value);
                    qRow++;
                }

                tran.Commit();
                
            }
            sw.Stop();

            long fl = (new FileInfo(e1dbPath)).Length;
            long diffFl = fl - 3867915; //file of first t1 - price
            Console.WriteLine("//DONE: FileLen: {0} bytes; CopyTableSize {1}; {2} ms; {3} bytes/row; {4} ms/row", fl, diffFl, sw.ElapsedMilliseconds, diffFl / qRow, sw.ElapsedMilliseconds / qRow);

            e1.Dispose();
            e1 = null;
            //DONE: FileLen: 4064523 bytes; 27573 ms; 4064 bytes/row; 27 ms/row -  INSERT
            //DONE: FileLen: 4220998 bytes; CopyTableSize 353083; 207 ms; 353 bytes/row; 0 ms/row  - COPY

        }

        private void TestSelectSomething()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                //var tr = tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ, 158000).Take(1).FirstOrDefault();
                
                //Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);

                foreach (var tr in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ).Take(10))
                {
                    Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);
                }
            }
        }


        private void TestSomeInsertsAndSomeDeletesAndFileSize()
        {
            File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }


            //this.InsertSequentialValues(2000);

            //e1.Scheme.DeleteTable("t1", true);

            //this.InsertSequentialValues(2000);

            //e1.Scheme.DeleteTable("t1", true);

            //this.InsertSequentialValues(2000000);

            //e1.Scheme.DeleteTable("t1", true);

            //this.InsertSequentialValues(1000000);
            //this.InsertSequentialValues(1000000);

            //e1.Scheme.DeleteTable("t1", true);

            //this.InsertSequentialValues(2000000);

            //this.InsertSequentialValues();

            //e1.Dispose();
            //e1 = null;
        }

        private void TestInsertAndDeleteFile()
        {
            //FOR STS

            File.Delete(dbPath);
            STSdb.Data.StorageEngine engine = StorageEngine.FromFile(dbPath);
            XTable<long, string> table = engine.Scheme.CreateOrOpenXTable<long, string>(new Locator("t1"));
            //IF NEXT LINE REMARKED THEN WORKS, IF NOT THEN  - CHECK IT
            XTable<long, string> table1 = engine.Scheme.CreateOrOpenXTable<long, string>(new Locator("t1"));
            engine.Scheme.Commit();

            table[123] = "dssfsd";
            table.Commit();

            

            engine.Scheme.Delete(new Locator("t1"));
            engine.Scheme.Commit();

            table1.Close();
            table.Close();

            table.RawFile.Close();
            engine.FileSystem.DeleteFile(table.RawFile.Handle);

            //XTable<long, string> table = engine.Scheme.OpenXTable<long, string>(new Locator("t1"));

            //Console.WriteLine(table[123]);

            //t

            //table

            //3	table.RawFile.Close();
            //4	engine.FileSystem.DeleteFile(table.RawFile.Handle);
            

        }

        #endregion



        #region "TestExhale"

        private void ReadLongTime()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }


            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {
                int i = 0;
                foreach (var tr in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ).Take(300))
                {
                    Console.WriteLine("%%%% {2}; K: {0}; V: {1};", tr.Key, tr.Value,i);
                    i++;
                }
            }
        }


        private void WriteSometimes()
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }
                   

            for (int i = 0; i < 1000; i++)
            {
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    for (int j = 1; j <= 5; j++)
                    {
                        //Console.WriteLine("index: " + ((i*10)  + j).ToString());
                        tran.Insert<long, string>("t1", ((i * 10) + j), "dslk fjsldkfj lsdkfj lskdjf slkdjf");
                    }

                    Console.WriteLine("µµµµµµµµµµµµµµµµµ   saving " + i.ToString());
                    tran.Commit();
                }
            }
        }

        private void Write3Accounts(string threadName)
        {
            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            for (int i = 1; i <= 50; i++)
            {
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {
                    tran.RegisterWriteOrSynchroReadTables("account/1", "account/2", "account/3");

                    var tr1 = tran.Select<int, int>("account/1", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
                    tr1.Value = tr1.Value + 1;

                    var tr2 = tran.Select<int, int>("account/2", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
                    tr2.Value = tr2.Value + 1;

                    var tr3 = tran.Select<int, int>("account/3", STSdb.MTL.eSelectMode.READ_SYNCHRO, 1);
                    tr3.Value = tr3.Value + 1;

                    tran.Commit();
                }

                Console.WriteLine("Thread: {0}; Itereation {1} is finished", threadName, i);
            }

            // using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    var tr = tran.Select<int, int>("account/1", STSdb.MTL.eSelectMode.READ, 1);
            //}
        }

        private void TestExhale()
        {
            //File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            //Action Write3Accounts1 = () =>
            //    {
            //        Write3Accounts("1");
            //    };

            //Write3Accounts1.DoAsync();

            //Action Write3Accounts2 = () =>
            //{
            //    Write3Accounts("2");
            //};

            //Write3Accounts2.DoAsync();

            //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    var tr1 = tran.Select<int, int>("account/1", STSdb.MTL.eSelectMode.READ, 1);
            //    var tr2 = tran.Select<int, int>("account/2", STSdb.MTL.eSelectMode.READ, 1);
            //    var tr3 = tran.Select<int, int>("account/3", STSdb.MTL.eSelectMode.READ, 1);
            //}

            //e1.Scheme.Exhale("account/1");

            return;

            //WriteSometimes();

            //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    ulong sd = tran.Count<long, string>("t1");

            //    foreach (var tr in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ))
            //    {
            //        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);

            //    }
            //}
            //return;
            //return;

            //Action writeLong = () =>
            //    {
            //        WriteSometimes();
            //    };

            //writeLong.DoAsync();

            //System.Threading.Thread.Sleep(3000);

            //e1.Scheme.Exhale("t1");

            //Console.WriteLine("t1 inserting 2000000");
            //InsertSequentialValues(2000000, "t1");

            //Action readLonggg = () =>
            //    {
            //        ReadLongTime();
            //    };

            //readLonggg.DoAsync();
            //return;

            //System.Threading.Thread.Sleep(2000);

            //e1.Scheme.Exhale("t1");

            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {

                var tr1 = tran.Select<long, string>("t1", STSdb.MTL.eSelectMode.READ, 1);

                Console.WriteLine("%%%% {2}; K: {0}; V: {1};", tr1.Key, tr1.Value, 1);
                
            }

            return;
            try
            {
                using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                {

                    foreach (var tr in tran.SelectForward<string, string>("@sys_exhaledTables_Names", STSdb.MTL.eSelectMode.READ).Take(300))
                    {
                        Console.WriteLine("K: {0}; V: {1};", tr.Key, tr.Value);

                    }
                }
            }
            catch (Exception ex)
            {
            
            }

            using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            {

                var tr = tran.Select<long, string>("t1", STSdb.MTL.eSelectMode.READ, 1);
                Console.WriteLine("%%%% {2}; K: {0}; V: {1};", tr.Key, tr.Value, 1);
                //tran.Select<long, byte[]>("@sys_etn_634637906350690630/t1", STSdb.MTL.eSelectMode.READ, 1);
            }

           

            //e1.Scheme.Exhale("t1");

            //InsertRandomValues(100000, 10, "t1", false, true);

            return;



            InsertSequentialValues(2000000,"t1");

            //Action readLonggg = () =>
            //    {
            //        ReadLongTime(); 
            //    };

            //readLonggg.DoAsync();


            //Action writeLonggg = () =>
            //{
            //    WriteSometimes();
            //};

            //writeLonggg.DoAsync();
           

            //Console.WriteLine("---------------------");
            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}
            //Console.WriteLine("---------------------");

            //Console.WriteLine("exhale");
            //e1.Scheme.Exhale("t1");
            //Console.WriteLine("exhale done");

            //TestSelectSomething();


            InsertSequentialValues(2000000,"t2");

            //Console.WriteLine("---------------------");
            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}
            //Console.WriteLine("---------------------");

            //Console.WriteLine("exhale");
            //e1.Scheme.Exhale("t1");
            //Console.WriteLine("exhale done");

            InsertSequentialValues(2000000,"t3");

            //Console.WriteLine("---------------------");
            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}
            //Console.WriteLine("---------------------");

            Console.WriteLine("exhale");
            //e1.Scheme.Exhale("t1");
            Console.WriteLine("exhale done");

            //InsertSequentialValues(2000000);

            Console.WriteLine("---------------------");
            foreach (var tn in e1.Scheme.GetAllTablesNames())
            {
                Console.WriteLine(tn);
            }
            Console.WriteLine("---------------------");

            //Console.WriteLine("exhale");
            //e1.Scheme.Exhale("t1");
            //Console.WriteLine("exhale done");

            //InsertSequentialValues(2000000);

            //Console.WriteLine("---------------------");
            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}
            //Console.WriteLine("---------------------");

            //Console.WriteLine("exhale");
            //e1.Scheme.Exhale("t1");
            //Console.WriteLine("exhale done");

            //InsertSequentialValues(2000000);

            //Console.WriteLine("---------------------");
            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}
            //Console.WriteLine("---------------------");

            //Console.WriteLine("exhale");
            //e1.Scheme.Exhale("t1");
            //Console.WriteLine("exhale done");

            //InsertSequentialValues(2000000);

            //Console.WriteLine("---------------------");
            //foreach (var tn in e1.Scheme.GetAllTablesNames())
            //{
            //    Console.WriteLine(tn);
            //}
            //Console.WriteLine("---------------------");

        }

        private void TestReadLocatorHandler()
        {
            File.Delete(e1dbPath);

            if (e1 == null)
            {
                e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            }

            //Action writeLonggg = () =>
            //{
            //    InsertSequentialValues(10000);
            //};
            //writeLonggg.DoAsync();


            Action readLonggg = () =>
            {
                
                    using (STSdb.MTL.Transaction tran = e1.GetTransaction())
                    {
                        for (int i = 0; i < 100; i++)
                        {
                            foreach (var tr in tran.SelectForward<long, string>("t1", STSdb.MTL.eSelectMode.READ).Take(100))
                            {
                                Console.WriteLine("%%%% {2}; K: {0}; V: {1};", tr.Key, tr.Value, i);                                
                            }
                        }
                    }
            };

            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(readLonggg);
            //readLonggg.DoAsync();


            //Action writeLonggg = () =>
            //{
            //    WriteSometimes();
            //};

            //writeLonggg.DoAsync();
        }

        //private void CreateEmptyTables()
        //{
        //    //File.Delete(e1dbPath);

        //    if (e1 == null)
        //    {
        //        e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
        //    }

        //    //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
        //    //{

        //    //    long tm = 0;

        //    //    for (int j = 0; j < 100; j++)
        //    //    {
        //    //        for (int i = 0; i < 1000; i++)
        //    //        {
        //    //            tm = DateTime.Now.Ticks;
        //    //            tran.Insert<long, string>("t" + j.ToString(), tm, tm.ToString() + "sdf jsdlkfj lsdkjflskdjf erui fuirhkfjh ydlfk" + tm.ToString() + "jg vcm,bcm,xbdfukgh eruit whghfdkln,cmvbncv,.xmbnfkjdgh urie " + tm.ToString());
        //    //        }
        //    //    }

        //    //    tran.Commit();
        //    //}

        //    //return;

        //    using (STSdb.MTL.Transaction tran = e1.GetTransaction())
        //    {
        //        for (int i = 0; i < 100; i++)
        //        {
        //            var tr = tran.Select<long, string>("t" + i.ToString(), STSdb.MTL.eSelectMode.READ, i);
        //            Console.WriteLine("K: {0}; V: {1}; tbl: {2};", tr.Key, tr.Value, i);
        //        }

        //        foreach (var tn in e1.Scheme.GetAllTablesNames())
        //        {
        //            Console.WriteLine(tn);
        //        }
        //    }



        //}

        #endregion

        #region "test DataBreezing"

        private void testDataBreezing()
        {
            //long l = 158546878;
            ////"#,#.00#;(#,#.00#)" ;(#,#.00#) .ToString("#,#.00#")
            //string a = String.Format("{0:#,#.#}", l);
            //Console.WriteLine(a);
            //return;
            //if (e1 == null)
            //{
            //    e1 = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            //}

            //using (STSdb.MTL.Transaction tran = e1.GetTransaction())
            //{
            //    //var c = tran.Count<byte[], byte[]>("t1");
            //    var c = tran.Count<long, byte[]>("t1");
            //}

            //return;
            File.Delete(e1dbPath);
           
            STSdbMTL_TestManager _t = new STSdbMTL_TestManager(e1dbPath);

            ulong TotalCountOfRecordsInTheTable = 0;
            long FileLength_Before = 0;
            long FileLength_After = 0;
            long insertCycleTime = 0;
            long compactCycleTime = 0;

            STSdb.MTL.TableCompactingResult cr = null;
            string toSave = String.Empty;

            //_t.CREATE_EMPTY_TABLES(3000, "t", true);

            //_t.SCHEMA_GetTableNames();

            //_t.Insert_Sequential_LongKey_RandomByteValues(1000000, "t1", 150, true);


            ////RANDOM INSERT
            //for (int j = 0; j < 10; j++)
            //{

            //    for (int i = 0; i < 10; i++)
            //    {
            //        _t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true, true);
            //    }

            //    Console.WriteLine("");
            //    Console.WriteLine("-----FL BEFORE COMPACTING: {0:#,#.#} bytes", new FileInfo(e1dbPath).Length);
            //    _t.Engine.Scheme.Exhale("t1");
            //    Console.WriteLine("-----FL AFTER COMPACTING: {0:#,#.#} bytes", new FileInfo(e1dbPath).Length);
            //    Console.WriteLine("");
            //}

            //////SEQUENTIAL INSERT
            //for (int j = 0; j < 10; j++)
            //{

            //    for (int i = 0; i < 10; i++)
            //    {
            //        _t.Insert_Sequential_LongKey_RandomByteValues(100000, "t1", 150, true, true);
            //        //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);
            //    }
                               

            //    Console.WriteLine("");
            //    Console.WriteLine("-----FL BEFORE COMPACTING: {0:#,#.#} bytes", new FileInfo(e1dbPath).Length);
            //    _t.Engine.Scheme.Exhale("t1");
            //    Console.WriteLine("-----FL AFTER COMPACTING: {0:#,#.#} bytes", new FileInfo(e1dbPath).Length);
            //    Console.WriteLine("");
            //}

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            
            FileStream fs = new FileStream(@"D:\temp\STS\stat_"+DateTime.Now.Ticks+".csv", FileMode.Append, FileAccess.Write);
            byte[] fsByte =null;
            ////SEQUENTIAL INSERT 2
            for (int j = 0; j < (580); j++)             //insertinf 365 days 365*10
            {

                sw.Reset();
                sw.Start();
                for (int i = 0; i < 1440; i++)      //1440 - quantity of minutes per day
                {
                    TotalCountOfRecordsInTheTable = _t.Insert_Sequential_LongKey_RandomByteValues(1, "t1", 150, true, false);
                    //TotalCountOfRecordsInTheTable = _t.Insert_Random_ByteKey_RandomByteValues(1, 8, 150, "t1", true,false);
                }

                sw.Stop();
                //Console.WriteLine("Insert 1440 block: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                insertCycleTime = sw.ElapsedMilliseconds;

                //Console.WriteLine("");
                FileLength_Before = new FileInfo(e1dbPath).Length;
                //Console.WriteLine("-----FL BEFORE COMPACTING: {0:#,#.#} bytes; TotRecords: {2:#,#.#}; {1:#,#.#} bytes/row; cycle {3}", FileLength, ((ulong)FileLength / TotalCountOfRecordsInTheTable), TotalCountOfRecordsInTheTable, j);

                sw.Reset();
                sw.Start();
                //cr = _t.Engine.Scheme.Exhale("t1");
                sw.Stop();

                

                compactCycleTime = sw.ElapsedMilliseconds;

                //fsByte = System.Text.Encoding.ASCII.GetBytes(String.Format("{0};{1};{2};{3}\r\n", j, FileLength, TotalCountOfRecordsInTheTable, ((ulong)FileLength / TotalCountOfRecordsInTheTable)));
                //fs.Write(fsByte, 0, fsByte.Length);
                //fs.Flush();

                FileLength_After = new FileInfo(e1dbPath).Length;

                //Console.WriteLine("");
                //Console.WriteLine(cr.ToConsoleString());
                //Console.WriteLine(cr.ToCsvString());

                //toSave = String.Format("{0};{1}{2};{3};{4};{5};{6};{7};{8};", j, cr.ToCsvString(), FileLength_Before, FileLength_After, ((cr.RecordsCount == 0) ? 0 : (ulong)FileLength_Before / cr.RecordsCount), ((cr.RecordsCount == 0) ? 0 : (ulong)FileLength_After / cr.RecordsCount), compactCycleTime, insertCycleTime, ((cr.TS_After == 0) ? (ulong)FileLength_After / cr.TS_Before : (ulong)FileLength_After / cr.TS_After));
                toSave = String.Format("Rec: {0}; FL: {1}", TotalCountOfRecordsInTheTable, FileLength_After);
                Console.WriteLine(toSave);
                //Console.WriteLine("");

                //Console.WriteLine("-----FL AFTER COMPACTING: {0:#,#.#} bytes; TotRecords: {2:#,#.#}; {1:#,#.#} bytes/row; cycle {3}; ins: {4}; comp: {5}", FileLength, ((ulong)FileLength / TotalCountOfRecordsInTheTable), TotalCountOfRecordsInTheTable, j,insertCycleTime,compactCycleTime);
                //Console.WriteLine("");

                //{4} insert dt; {5} compact dt

                fsByte = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", toSave));
                fs.Write(fsByte, 0, fsByte.Length);
                fs.Flush();
            }

            fs.Flush();
            fs.Close();
            fs.Dispose();


            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);
            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);
            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);

            //_t.Select_READ_FromTable<long, byte[]>("t1", 100);

            //_t.Engine.Scheme.Exhale("t1");


            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);

            //_t.Engine.Scheme.Exhale("t1");

            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);

            //_t.Engine.Scheme.Exhale("t1");
           
         }


        private void ReadSome()
        {
            lock (sync_txxx)
            {
                if (_txxx == null)
                    _txxx = new STSdbMTL_TestManager(e1dbPath);
            }

            for (int i = 0; i < 1000000; i++)
            {
                using (var tran = _txxx.Engine.GetTransaction())
                {
                    var tr = tran.SelectBackward<long, byte[]>("t1", STSdb.MTL.eSelectMode.READ).Take(1).FirstOrDefault();
                    if (tr != null)
                    {
                        Console.WriteLine("T1: {0};", tr.Key);
                    }
                    
                }

                System.Threading.Thread.Sleep(1000);
            }
        }

        STSdbMTL_TestManager _txxx = null;
        object sync_txxx = new object();
        private void testDataBreezingV2(string tableName)
        {
            STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = true;
            STSdb.MTL.StsTablesCompactor._MIN_QUANTITY_FOR_COMPACTION_START = 100;
            STSdb.MTL.StsTablesCompactor.COMPACTION_DIFF_BETWEEN_COMPACTS_IN_MINUTES = 0;
            //STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = false;

            //File.Delete(e1dbPath);

            lock (sync_txxx)
            {
                if (_txxx == null)
                    _txxx = new STSdbMTL_TestManager(e1dbPath);
            }

            //using (var tran = _txxx.Engine.GetTransaction())
            //{
            //    tran.Select<long, byte[]>("t1", STSdb.MTL.eSelectMode.READ, 1);
            //    tran.Select<long, byte[]>("t2", STSdb.MTL.eSelectMode.READ, 1);
            //    tran.Select<long, byte[]>("t3", STSdb.MTL.eSelectMode.READ, 1);
            //}
            //return;

            ulong TotalCountOfRecordsInTheTable = 0;
            long FileLength_Before = 0;
            long FileLength_After = 0;
            long insertCycleTime = 0;
            long compactCycleTime = 0;

            STSdb.MTL.TableCompactingResult cr = null;
            string toSave = String.Empty;


            System.Diagnostics.Stopwatch sw = new Stopwatch();

            Random rnd = new Random();
            byte[] toInsert = new byte[150];
            //byte[] toInsert = new byte[1];

            ulong prevCount = 0;
            

            //FileStream fs = new FileStream(@"D:\temp\STS\stat_" + DateTime.Now.Ticks + ".csv", FileMode.Append, FileAccess.Write);
            //byte[] fsByte = null;
            ////SEQUENTIAL INSERT 2
            long k = 1;
            for (int j = 0; j < (500); j++)             //insertinf 365 days 365*10
            {

                sw.Reset();
                sw.Start();
                //using (var tran = _txxx.Engine.GetTransaction())
                //{
                //    TotalCountOfRecordsInTheTable = tran.Count<long, byte[]>(tableName, true);
                //    Console.WriteLine(String.Format("before: {0}, {1}", tableName, TotalCountOfRecordsInTheTable));
                //}
                for (int i = 0; i < 1440; i++)      //1440 - quantity of minutes per day
                {
                    using (var tran = _txxx.Engine.GetTransaction())
                    {                        
                        //DateTime;  TableName;  Table1ReadyToSave;1 - Table 1 Saved or 0;    Table2ReadToSave;0/1 - Table 2 Save;  Compactor tableName; 1 - Started; 1 - Finished; quantity records

                        //STSdb.MTL.Utils.Files.FileLogger.WriteToFileLoggerAscii(
                        //        String.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};\r\n",
                        //        DateTime.Now.Ticks,
                        //        tableName,
                        //        (tableName == "t1") ? 1 : 0,    //Table1ReadyToSave
                        //        0,  //1 - Table 1 Saved or 0
                        //        (tableName == "t2") ? 1 : 0,     //Table2ReadyToSave,
                        //        0,  //1 - Table 2 Saved or 0
                        //        "",                              //Compactor tableName
                        //        0,                              //Compactor started
                        //        0,                                //Compactor finished
                        //        0
                        //        )
                        //    );
                       

                        //Console.WriteLine("write started " + tableName);
                        rnd.NextBytes(toInsert);
                        try
                        {
                            //if (tableName == "t3")
                            //    Console.WriteLine("Before insert");
                            TotalCountOfRecordsInTheTable = tran.Count<long, byte[]>(tableName, true);
                            tran.Insert<long, byte[]>(tableName, k, toInsert);
                            //if (tableName == "t3")
                            //    Console.WriteLine(String.Format("--------------------------------------------------Commit started: {0}; Rec: {1}; ThreadId: {2}", tableName, TotalCountOfRecordsInTheTable, System.Threading.Thread.CurrentThread.ManagedThreadId));
                            tran.Commit();

                            TotalCountOfRecordsInTheTable = tran.Count<long, byte[]>(tableName, true);
                            //if (tableName == "t3")
                            //    Console.WriteLine(String.Format("--------------------------------------------------Commit finished: {0}; Rec: {1}", tableName, TotalCountOfRecordsInTheTable));

                            //if (tableName == "t3")
                            //{
                            //    if (prevCount != (TotalCountOfRecordsInTheTable - 1))
                            //    {
                            //        Console.WriteLine("***********************************************************************");
                            //    }
                            //}

                            if (prevCount != (TotalCountOfRecordsInTheTable - 1))
                            {
                                Console.WriteLine(String.Format("*********************************************************************** Table {0}; Thread: {1};", tableName, System.Threading.Thread.CurrentThread.ManagedThreadId));
                            }

                            prevCount = TotalCountOfRecordsInTheTable;
                            
                            //TotalCountOfRecordsInTheTable = 1;
                            k++;
                        }
                        catch (Exception ex)
                        {
                            
                        }
                        


                        //DateTime;Table1ReadyToSave;1 - Table 1 Saved or 0; Table2ReadToSave;0/1 - Table 2 Save;Compactor tableName; 1 - Started; 1 - Finished

                        //STSdb.MTL.Utils.Files.FileLogger.WriteToFileLoggerAscii(
                        //        String.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};\r\n",
                        //        DateTime.Now.Ticks,
                        //        tableName,
                        //        0,                              //Table1ReadyToSave
                        //        (tableName == "t1") ? 1 : 0,   //1 - Table 1 Saved or 0
                        //        0,     //Table2ReadyToSave,
                        //        (tableName == "t2") ? 1 : 0,                              //1 - Table 2 Saved or 0
                        //        "",                              //Compactor tableName
                        //        0,                              //Compactor started
                        //        0,                                //Compactor finished
                        //        TotalCountOfRecordsInTheTable
                        //        )
                        //    );

                    }
                    //TotalCountOfRecordsInTheTable = _txxx.Insert_Sequential_LongKey_RandomByteValues(1, tableName, 150, true, false);
                    //TotalCountOfRecordsInTheTable = _t.Insert_Random_ByteKey_RandomByteValues(1, 8, 150, "t1", true,false);
                }

                //if (tableName == "t3")
                //{
                //    if ((ulong)((j + 1) * 1440) != TotalCountOfRecordsInTheTable)
                //    {

                //    }
                //}


                sw.Stop();
                //Console.WriteLine("Insert 1440 block: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                insertCycleTime = sw.ElapsedMilliseconds;

                //Console.WriteLine("");
                FileLength_Before = new FileInfo(e1dbPath).Length;
                //Console.WriteLine("-----FL BEFORE COMPACTING: {0:#,#.#} bytes; TotRecords: {2:#,#.#}; {1:#,#.#} bytes/row; cycle {3}", FileLength, ((ulong)FileLength / TotalCountOfRecordsInTheTable), TotalCountOfRecordsInTheTable, j);

                sw.Reset();
                sw.Start();
                //cr = _t.Engine.Scheme.Exhale("t1");
                sw.Stop();



                compactCycleTime = sw.ElapsedMilliseconds;

                //fsByte = System.Text.Encoding.ASCII.GetBytes(String.Format("{0};{1};{2};{3}\r\n", j, FileLength, TotalCountOfRecordsInTheTable, ((ulong)FileLength / TotalCountOfRecordsInTheTable)));
                //fs.Write(fsByte, 0, fsByte.Length);
                //fs.Flush();

                FileLength_After = new FileInfo(e1dbPath).Length;

                //Console.WriteLine("");
                //Console.WriteLine(cr.ToConsoleString());
                //Console.WriteLine(cr.ToCsvString());

                //toSave = String.Format("{0};{1}{2};{3};{4};{5};{6};{7};{8};", j, cr.ToCsvString(), FileLength_Before, FileLength_After, ((cr.RecordsCount == 0) ? 0 : (ulong)FileLength_Before / cr.RecordsCount), ((cr.RecordsCount == 0) ? 0 : (ulong)FileLength_After / cr.RecordsCount), compactCycleTime, insertCycleTime, ((cr.TS_After == 0) ? (ulong)FileLength_After / cr.TS_Before : (ulong)FileLength_After / cr.TS_After));

                toSave = String.Format("TN: {2}; Rec: {0}; FL: {1}; j: {3}; time {4} ms; bpr: {5} ", TotalCountOfRecordsInTheTable, FileLength_After, tableName, j, insertCycleTime, (ulong)FileLength_After / (TotalCountOfRecordsInTheTable*3));
                Console.WriteLine(toSave);
                //Console.WriteLine("");

                //Console.WriteLine("-----FL AFTER COMPACTING: {0:#,#.#} bytes; TotRecords: {2:#,#.#}; {1:#,#.#} bytes/row; cycle {3}; ins: {4}; comp: {5}", FileLength, ((ulong)FileLength / TotalCountOfRecordsInTheTable), TotalCountOfRecordsInTheTable, j,insertCycleTime,compactCycleTime);
                //Console.WriteLine("");

                //{4} insert dt; {5} compact dt

                //fsByte = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", toSave));
                //fs.Write(fsByte, 0, fsByte.Length);
                //fs.Flush();
            }


            using (var tran = _txxx.Engine.GetTransaction())
            {
                var c = tran.Count<long, byte[]>(tableName);
                Console.WriteLine(tableName + ":" + c.ToString());
            }

            //fs.Flush();
            //fs.Close();
            //fs.Dispose();


            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);
            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);
            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);

            //_t.Select_READ_FromTable<long, byte[]>("t1", 100);

            //_t.Engine.Scheme.Exhale("t1");


            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);

            //_t.Engine.Scheme.Exhale("t1");

            //_t.Insert_Random_ByteKey_RandomByteValues(10000, 8, 150, "t1", true);

            //_t.Engine.Scheme.Exhale("t1");

        }

        private void parallelReadWithDataBreazingV2()
        {
            lock (sync_txxx)
            {
                if (_txxx == null)
                    _txxx = new STSdbMTL_TestManager(e1dbPath);
            }
            ulong cnt = 0;

            //Console.WriteLine("___READ___Thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
            while (true)
            {
                using (var tran = _txxx.Engine.GetTransaction())
                {
                    cnt = tran.Count<long, byte[]>("t1", false);
                    cnt = tran.Count<long, byte[]>("t2", false);
                    cnt = tran.Count<long, byte[]>("t3", false);
                }
            }
        }



        private void testDataBreezing_UpdatingOneValue(string tableName)
        {
            STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = true;
            STSdb.MTL.StsTablesCompactor._MIN_QUANTITY_FOR_COMPACTION_START = 10;
            //File.Delete(e1dbPath);

            lock (sync_txxx)
            {
                if (_txxx == null)
                    _txxx = new STSdbMTL_TestManager(e1dbPath);
            }

            ulong TotalCountOfRecordsInTheTable = 0;
            long FileLength_Before = 0;
            long FileLength_After = 0;
            long insertCycleTime = 0;
            long compactCycleTime = 0;

            STSdb.MTL.TableCompactingResult cr = null;
            string toSave = String.Empty;

            System.Diagnostics.Stopwatch sw = new Stopwatch();


            //FileStream fs = new FileStream(@"D:\temp\STS\stat_" + DateTime.Now.Ticks + ".csv", FileMode.Append, FileAccess.Write);
            //byte[] fsByte = null;

            Random rnd=new Random();
            byte[] btValue=new byte[150];

            ////SEQUENTIAL INSERT 2
            for (int j = 0; j < (7114); j++)             //inserting j cycles, j quantity of days
            {

                sw.Reset();
                sw.Start();
                for (int i = 0; i < 1440; i++)      //1440 - quantity of minutes per day
                {
                    using (var tran = _txxx.Engine.GetTransaction())
                    {
                        rnd.NextBytes(btValue);
                        tran.Insert<long, byte[]>(tableName, 4565654654, btValue);
                        tran.Commit();

                        TotalCountOfRecordsInTheTable = tran.Count<long, byte[]>(tableName);
                    }

                    TotalCountOfRecordsInTheTable = 1;
                    //TotalCountOfRecordsInTheTable = _t.Insert_Sequential_LongKey_RandomByteValues(1, "t1", 150, true, false);
                    //TotalCountOfRecordsInTheTable = _t.Insert_Random_ByteKey_RandomByteValues(1, 8, 150, "t1", true,false);
                }

                sw.Stop();                

                insertCycleTime = sw.ElapsedMilliseconds;
              
                FileLength_Before = new FileInfo(e1dbPath).Length;              

                //sw.Reset();
                //sw.Start();
                ////cr = _t.Engine.Scheme.Exhale("t1");
                //sw.Stop();

                compactCycleTime = sw.ElapsedMilliseconds;                            

                FileLength_After = new FileInfo(e1dbPath).Length;

                //toSave = String.Format("{0};{1}{2};{3};{4};{5};{6};{7};{8};", j, cr.ToCsvString(), FileLength_Before, FileLength_After, ((cr.RecordsCount == 0) ? 0 : (ulong)FileLength_Before / cr.RecordsCount), ((cr.RecordsCount == 0) ? 0 : (ulong)FileLength_After / cr.RecordsCount), compactCycleTime, insertCycleTime, ((cr.TS_After == 0) ? (ulong)FileLength_After / cr.TS_Before : (ulong)FileLength_After / cr.TS_After));
                toSave = String.Format("TN: {2}; Rec: {0}; FL: {1}; j: {3}; time {4} ms; bpr: {5} ", TotalCountOfRecordsInTheTable, FileLength_After, tableName, j, insertCycleTime, (ulong)FileLength_After / (TotalCountOfRecordsInTheTable * 3));
                Console.WriteLine(toSave);
             

                //fsByte = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", toSave));
                //fs.Write(fsByte, 0, fsByte.Length);
                //fs.Flush();
            }

            //fs.Flush();
            //fs.Close();
            //fs.Dispose();

        }



        private void NativeSTSCompact()
        {
            string dbPath = @"D:\temp\STS\e1.stsdb";

            File.Delete(dbPath);

            XTable<long, byte[]> table = null;
            XTable<long, byte[]> tableNext = null;
            Locator l = null;
            Locator lNext = null;
            long key = 0;
            byte[] bt = new byte[150];
            Random rnd = new Random();
            string newLocatorName = String.Empty;
            ulong FileHandle=0;
            ulong recordsCount=0;
            ulong wastedSpace = 0;
            ulong rawFileLength = 0;
            ulong tableSize = 0;
            ulong newRawFileSize = 0;
            long dbFileLengthBeforeCompact = 0;
            long dbFileLengthAfterCompact = 0;

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            //STSdb.Data.Transaction internalTransaction = null;

            using (StorageEngine engine = StorageEngine.FromFile(dbPath))
            {              

                for (int j = 0; j < 1000; j++)             //inserting 1000 days
                {
                    l = new Locator("t" + j.ToString());

                    table = engine.Scheme.CreateOrOpenXTable<long, byte[]>(l);

                    engine.Scheme.Commit();

                    key = DateTime.Now.Ticks;

                    sw.Reset();
                    sw.Start();

                    for (int i = 0; i < 1440; i++)      //1440 - quantity of minutes per day
                    {
                        key++;
                        rnd.NextBytes(bt);
                        table[key] = bt;


                        //if to make it via transaction.Commit takes 27 000 ms for 1440 records                   
                        //internalTransaction = new Transaction(engine, table);
                        //internalTransaction.Commit();
                        
                        //if to make it via table.Commit, takes 2504 ms for 1440 records
                        table.Commit();
                        
                    }

                    sw.Stop();
                    Console.WriteLine("Insert 1440 block: {0} ms; {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks);

                    //calculating some values for the table before its deleting
                    dbFileLengthBeforeCompact = (new FileInfo(dbPath)).Length;
                    rawFileLength = table.RawFile.Length;
                    tableSize = table.Size;
                    wastedSpace = table.RawFile.Length - table.Size;
                    recordsCount = table.Count;                    

                    //copying table to t + nextValue
                    newLocatorName = "t" + (j + 1).ToString();
                    lNext = new Locator(newLocatorName);

                    //opening new table
                    tableNext = engine.Scheme.CreateOrOpenXTable<long, byte[]>(lNext);
                    engine.Scheme.Commit();

                    foreach (var tr in table.Forward())
                    {
                        tableNext[tr.Key] = tr.Record;
                    }
                    
                    tableNext.Commit();

                    newRawFileSize = tableNext.RawFile.Length;

                    //deleting t+"j" from the scheme 
                    //engine.Scheme.Delete(l);
                    engine.Scheme.Delete(new Locator("t" + j.ToString()));
                    engine.Scheme.Commit();

                    FileHandle = table.RawFile.Handle;
                    
                    //releasing BOTH files locks
                    table.RawFile.Close();
                    tableNext.RawFile.Close();

                    //deleting table from the system
                    engine.FileSystem.DeleteFile(FileHandle);

                    dbFileLengthAfterCompact = new FileInfo(dbPath).Length;
                    Console.WriteLine(" Table {0} is created; RecordsCount: {1:#,#.#}; PrevTableWasted: {2:#,#.#}; RawFileLength: {3:#,#.#}; TableSize {4:#,#.#}; FullDbFileLengthBeforeCompact: {7:#,#.#}; FullDbFileLength: {5:#,#.#}; NewRawFileLength: {6:#,#.#}; Bytes/row: {8:#,#.#}", newLocatorName, recordsCount, wastedSpace, rawFileLength, tableSize, dbFileLengthAfterCompact, newRawFileSize, dbFileLengthBeforeCompact, ((ulong)dbFileLengthAfterCompact - ((ulong)j * 64000)) / recordsCount);
                    //Console.WriteLine(" Table {0} is created; RecordsCount: {1:#,#.#}; PrevTableWasted: {2:#,#.#}; RawFileLength: {3:#,#.#}; TableSize {4:#,#.#}; FullDbFileLengthBeforeCompact: {7:#,#.#}; FullDbFileLength: {5:#,#.#}; NewRawFileLength: {6:#,#.#}; Bytes/row: {8:#,#.#}", newLocatorName, recordsCount, wastedSpace, rawFileLength, tableSize, dbFileLengthAfterCompact, newRawFileSize, dbFileLengthBeforeCompact, (ulong)dbFileLengthAfterCompact / recordsCount);
                }

            }
        }



        private void NativeSTSCompact_V2()
        {
            string dbPath = @"D:\temp\STS\e1.stsdb";

            File.Delete(dbPath);

            XTable<long, byte[]> table = null;
            XTable<long, byte[]> tableNext = null;
            Locator l = null;
            Locator lNext = null;
            long key = 0;
            byte[] bt = new byte[150];
            Random rnd = new Random();
            string newLocatorName = String.Empty;
            ulong FileHandle = 0;
            ulong recordsCount = 0;
            ulong wastedSpace = 0;
            ulong rawFileLength = 0;
            ulong tableSize = 0;
            ulong newRawFileSize = 0;
            long dbFileLengthBeforeCompact = 0;

            using (StorageEngine engine = StorageEngine.FromFile(dbPath))
            {

                for (int j = 0; j < 10; j++)             //inserting 10 days
                {
                    l = new Locator("t" + j.ToString());

                    table = engine.Scheme.CreateOrOpenXTable<long, byte[]>(l);

                    engine.Scheme.Commit();

                    engine.Scheme.OpenXTable<long, byte[]>(new Locator("t" + j.ToString()));

                    key = DateTime.Now.Ticks;

                    for (int i = 0; i < 1440; i++)      //1440 - quantity of minutes per day
                    {
                        key++;
                        rnd.NextBytes(bt);
                        table[key] = bt;

                        table.Commit();

                        //table.Close();
                        //table.RawFile.Close();
                        table = engine.Scheme.OpenXTable<long, byte[]>(new Locator("t" + j.ToString()));
                        engine.Scheme.OpenXTable<long, byte[]>(new Locator("t" + j.ToString()));
                    }

                    //calculating some values for the table before its deleting
                    dbFileLengthBeforeCompact = (new FileInfo(dbPath)).Length;
                    rawFileLength = table.RawFile.Length;
                    tableSize = table.Size;
                    wastedSpace = table.RawFile.Length - table.Size;
                    recordsCount = table.Count;

                    //copying table to t + nextValue
                    newLocatorName = "t" + (j + 1).ToString();
                    lNext = new Locator(newLocatorName);

                    //opening new table
                    tableNext = engine.Scheme.CreateOrOpenXTable<long, byte[]>(lNext);
                    engine.Scheme.Commit();

                    foreach (var tr in table.Forward())
                    {
                        tableNext[tr.Key] = tr.Record;
                    }

                    tableNext.Commit();

                    newRawFileSize = tableNext.RawFile.Length;

                    //deleting t+"j" from the scheme 
                    //engine.Scheme.Delete(l);
                    engine.Scheme.Delete(new Locator("t" + j.ToString()));
                    engine.Scheme.Commit();

                    FileHandle = table.RawFile.Handle;

                    //releasing BOTH files locks
                    table.RawFile.Close();
                    tableNext.RawFile.Close();

                    //deleting table from the system
                    engine.FileSystem.DeleteFile(FileHandle);

                    Console.WriteLine(" Table {0} is created; RecordsCount: {1:#,#.#}; PrevTableWasted: {2:#,#.#}; RawFileLength: {3:#,#.#}; TableSize {4:#,#.#}; FullDbFileLengthBeforeCompact: {7:#,#.#}; FullDbFileLength: {5:#,#.#}; NewRawFileLength: {6:#,#.#};", newLocatorName, recordsCount, wastedSpace, rawFileLength, tableSize, new FileInfo(dbPath).Length, newRawFileSize, dbFileLengthBeforeCompact);
                }

            }
        }


        private void insert10Mln()
        {
            File.Delete(e1dbPath);

            STSdbMTL_TestManager _t = new STSdbMTL_TestManager(e1dbPath);

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Reset();
            sw.Start();


            _t.Insert_Sequential_LongKey_RandomByteValues(2000000, "t1", 150, true, false);

            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);
        }

        private void select10mln()
        {

            //Select random 1MLN iterations/2MLN:  64 K sector 13 sec; 4096 - 109 sec; 512 - 125 sec.....Smallest File size with 4096 kb, Biggest 512 b
            //Insert time 2 MLN records : 

            STSdbMTL_TestManager _t = new STSdbMTL_TestManager(e1dbPath);

            System.Diagnostics.Stopwatch sw = new Stopwatch();

            sw.Reset();
            sw.Start();

            Random rnd=new Random();

            using(var tran = _t.Engine.GetTransaction())
            {
                var min = tran.MinRow<long, byte[]>("t1");
                var max = tran.MaxRow<long, byte[]>("t1");

                for (int i = 0; i<1000000; i++)
                {

                    var tr = tran.Select<long, byte[]>("t1", STSdb.MTL.eSelectMode.READ, ((long)rnd.Next(1999999) * 115754) + min.Key);
                }
            }


            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);
        }

        private void FileSystemTest()
        {
            StorageEngine _t = StorageEngine.FromFile(dbPath);
            ulong handle=0;
            var rf = _t.FileSystem.CreateFile();
            Random rnd=new Random();
            handle = rf.Handle;

            rf.Write(0, new byte[] { 1, 2, 4 }, 0, 3);
            rf.Flush();

            rf.Close();

            rf = _t.FileSystem.OpenFile(handle);
            byte[] readBt=new byte[3];
            rf.Read(0, readBt, 0, 3);

            rf.Close();

        }

        private void BigObjecT()
        {
            File.Delete(e1dbPath);

            STSdbMTL_TestManager _t = new STSdbMTL_TestManager(e1dbPath);

            using (var tran = _t.Engine.GetTransaction())
            {
                tran.Insert<int, string>("t1", 12, "sdf");
                tran.Commit();
                tran.UpdateValue<int, string>("t1", 12, "sdf32");
                tran.Commit();

                tran.Insert<int, string>("t1", 13, "sdf43543");
                tran.Insert<int, string>("t1", 14, "sdf576575");
                tran.Insert<int, string>("t1", 15, "sdf576575");
                tran.Insert<int, string>("t1", 16, "sdf576575");
                tran.Insert<int, string>("t1", 17, "sdf576575");

                tran.Commit();
            }

            using (var tran = _t.Engine.GetTransaction())
            {
                int i = 0;
                foreach (var tr in tran.SelectForward<int, string>("t1", STSdb.MTL.eSelectMode.READ))
                {
                    if (i == 2)
                        break;
                    Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                    i++;
                }
            }

        }


        private void testAsyncCompacting(string tableName)
        {
            //STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = true;
            STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = true;

            //File.Delete(e1dbPath);

            lock (sync_txxx)
            {
                if (_txxx == null)
                    _txxx = new STSdbMTL_TestManager(e1dbPath);
            }

            for (int i = 0; i < 1000; i++)
            {
                using (var tran = _txxx.Engine.GetTransaction())
                {
                    var tr = tran.Select<long,int>(tableName,STSdb.MTL.eSelectMode.READ_SYNCHRO,1);
                    tr.Value +=1;
                    tran.Commit();
                }

            }

            using (var tran = _txxx.Engine.GetTransaction())
            {
                var c = tran.Select<long, int>(tableName,STSdb.MTL.eSelectMode.READ_SYNCHRO,1);
                Console.WriteLine(tableName + ":" + c.Value.ToString());
            }
        }

        bool deleteFile = true;
        private void StarttestAsyncCompacting()
        {
            if(deleteFile)
                File.Delete(e1dbPath);
            deleteFile = false;
            

            Action a1 = () =>
                {
                    this.testAsyncCompacting("t1");
                };

            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a1);
            //a1.DoAsync();

            Action a2 = () =>
            {
                this.testAsyncCompacting("t1");
            };

            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a2);
            //a2.DoAsync();

            Action a3 = () =>
            {
                this.testAsyncCompacting("t1");
            };

            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a3);
            //a3.DoAsync();
        }
        #endregion




        //- !!!!!!!!!!!!!!!!!!!!!! copying DB rawFiles, engine must be stopped, run via special program, this run initializes engine and restores all
            //compactions and transactions, then copies tables and raw files
        //- Schema wrapper, which will not delete tables, also raw file + radix tree solution, so we can economize, when table compacts and create new table.
        //- Automatic run of compacter after 1500 inserts.
        //- Check if Exists etc.

        //- DON MAKE infinite loop inside of transaction...if you want so, better open transaction in every loop iteration.
        //- Test async compacting
        //Correct schema locks in Exhale Table get and put
        //Statistic for table
        //If in current state many tables in one raw we can't delete the raw file until all are moved to separate files
        //Logging exhale and restoring it
        //Storing systables in one raw file                        
        //Plan for breezing
        //look how correctly to close files
        //getting how much tables reside in one file (possible with schema[name]. will be file handle)
        //safe compacting of sys special tables
        //notes for users, don't use table names longer then 50-70 chars ASCII and @sys tables are reserved
        //Restore snapshots for one transaction
        //add version of MTL
        //check engine global lock for multithreading environment, check ability to create db in WSN constructor.
        //put all or some of empty tables into one raw file, @sys category one.
        //Take engine only via engines by name?
        //Check all OpenXTable non-generics correspondence to schema lock
        //Test speed of READ access with 512 sector


        #region "TESTASYNCMANYREADSMISTAKE"

        XTable<string, string> myxtable = null;
        //XTable<int, int> myxtable = null;
        string myxtable_stringName = "myTableName";
        StorageEngine se = null;
        object lock_myxtable = new object();

        private void InitTable()
        {
            File.Delete(e1dbPath);            
         
            se = StorageEngine.FromFile(e1dbPath);
            myxtable = se.Scheme.CreateOrOpenXTable<string, string>(new Locator(myxtable_stringName));
            //myxtable = se.Scheme.CreateOrOpenXTable<int, int>(new Locator(myxtable_stringName));
            se.Scheme.Commit();

            myxtable["t1"] = "sdfjsdlfkjsdlfj sl";
            myxtable["t2"] = "sdfjsdlfkjsddsdfsdfj sl";
            myxtable["t3"] = "sdfjsdlsadfasdfsadfasdsafkjsddsdfsdfj sl";
            //myxtable[1] = 1;
            //myxtable[2] = 2;
            //myxtable[3] = 3;
            myxtable.Commit();
        }

        private void InitTable2()
        {
            File.Delete(e1dbPath);


            _txxx = new STSdbMTL_TestManager(e1dbPath);

            using (var tran = _txxx.Engine.GetTransaction())
            {
                tran.Insert<string, string>(myxtable_stringName, "t1", "dsfsdfsdfsd");
                tran.Insert<string, string>(myxtable_stringName, "t2", "dsfsdfdsfsdfsdfsd");
                tran.Insert<string, string>(myxtable_stringName, "t3", "dsfsdasaafsdfsd");

                tran.Commit();
            }

            //se = StorageEngine.FromFile(e1dbPath);
            ////myxtable = se.Scheme.CreateOrOpenXTable<string, string>(new Locator(myxtable_stringName));
            //myxtable = se.Scheme.CreateOrOpenXTable<int, int>(new Locator(myxtable_stringName));
            //se.Scheme.Commit();

            //myxtable["t1"] = "sdfjsdlfkjsdlfj sl";
            //myxtable["t2"] = "sdfjsdlfkjsddsdfsdfj sl";
            //myxtable["t3"] = "sdfjsdlsadfasdfsadfasdsafkjsddsdfsdfj sl";
            //myxtable[1] = 1;
            //myxtable[2] = 2;
            //myxtable[3] = 3;
            //myxtable.Commit();
        }

       

        private void ReadIt1(object key)
        {
            bool couldGetValue = false;
            string stringValue = String.Empty;
            //int stringValue = 0;
            XTable<string, string> table = null;

            for (int i = 0; i < 100000; i++)
            {
                try
                {

                    //using (var tran = _txxx.Engine.GetTransaction())
                    //{
                    //    var tr = tran.Select<string, string>(myxtable_stringName, STSdb.MTL.eSelectMode.READ, Convert.ToString(key));
                    //    if (tr == null || !tr.Exists)
                    //    {

                    //    }
                    //}
                    
                    //lock (se.Scheme.SyncRoot)
                    //{
                    //    table = se.Scheme.OpenXTable<string, string>(new Locator(myxtable_stringName));
                    //}
                    //couldGetValue = table.TryGet(Convert.ToString(key), out stringValue);
                    //couldGetValue = myxtable.TryGet(Convert.ToInt32(key), out stringValue);

                    lock (lock_myxtable)
                    {
                        couldGetValue = myxtable.TryGet(Convert.ToString(key), out stringValue);
                    }
                }
                catch (Exception ex)
                {
                    //--------------------------- PUT A BREAKPOINT
                    //Exception: LinkedList node doesn't belong to the curernt LinkedList
                    //Occurs in FTable.Link.Touch()
                    throw ex;
                }
            }

            Console.WriteLine("DONE");
        }

        private void StartManyThreads()
        {           
            for (int i = 1; i <= 3; i++)
            {
                System.Threading.Thread tr = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ReadIt1));
                tr.Start("t" + i.ToString());         
                //tr.Start(i.ToString());  
            }
        }

        //private void StartManyThreads()
        //{
        //    //Action<string> a1 = (tableName) =>
        //    //    {
        //    //        ReadIt(tableName);
        //    //    };
                        

        //    for (int i = 1; i <= 3; i++)
        //    {      
        //        System.Threading.Thread tr = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ReadIt1));
        //        tr.Start("t" + i.ToString());

        //        //a1.DoAsync("t" + i.ToString());
        //    }
        //}


        //private void ReadIt(string originalUserTableName)
        //{
        //    bool couldGetValue = false;
        //    string ser_UserTableSchema = String.Empty;

        //    for (int i = 0; i < 100000; i++)
        //    {
        //        try
        //        {

        //            couldGetValue = myxtable.TryGet(originalUserTableName, out ser_UserTableSchema);
        //            //Console.WriteLine(ser_UserTableSchema);
        //        }
        //        catch (Exception ex)
        //        {

        //            throw ex;
        //        }
        //    }

        //    Console.WriteLine("DONE");
        //}

        #endregion


        #region "Testing Async"
        private void Insert1000Rows()
        {
            STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = false;

            File.Delete(e1dbPath);
            
            _txxx = new STSdbMTL_TestManager(e1dbPath);

            using (var tran = _txxx.Engine.GetTransaction())
            {
                for (int i = 0; i < 1000; i++)
                {
                    tran.Insert<int, string>("t1", i, "dsfsdfsdfsd"+i.ToString());
                }                

                tran.Commit();
            }
        }

        private void StartSelectOfThis1000(string it)
        {
            using (var tran = _txxx.Engine.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<int,string>("t1",STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine("It: {2}; K: {0}; V:{1}", tr.Key, tr.Value,it);
                }
                
            }
        }

        private void Insert200More()
        {
            using (var tran = _txxx.Engine.GetTransaction())
            {
                for (int i = 1010; i < 2000; i++)
                {
                    tran.Insert<int, string>("t1", i, "dsfsdfsdfsd" + i.ToString());
                }

                tran.Commit();
            }
        }
        #endregion

        #region "testing parallel commit"


        //XTable<string, string> myxtable1 = null;
        //XTable<string, string> myxtable2 = null;
                

        private void InitTable_PC()
        {
            //File.Delete(e1dbPath);

            if (se == null)
            {
                se = StorageEngine.FromFile(e1dbPath);
                var tbl1 = se.Scheme.CreateOrOpenXTable<string, string>(new Locator("t1"));
                se.Scheme.Commit();

                var tbl2 = se.Scheme.CreateOrOpenXTable<string, string>(new Locator("t2"));
                se.Scheme.Commit();

                var tbl3 = se.Scheme.CreateOrOpenXTable<string, string>(new Locator("t3"));
                se.Scheme.Commit();

                tbl1["1"] = "1";
                tbl1.Commit();

                tbl2["1"] = "1";
                tbl2.Commit();

                tbl3["1"] = "1";
                tbl3.Commit();
            }

            Action<string> a = (tableName)=>
            {
                var t = se.Scheme.CreateOrOpenXTable<string, string>(new Locator(tableName));    
                for (int i = 0; i < 10000; i++)
                {
                    t["1"] = DateTime.Now.ToString();
                    t.Commit();
                }

                Console.WriteLine(tableName + " done");
            };

            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a, "t1");
            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a, "t2");
            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a, "t3");
            //a.DoAsync("t1");
            //a.DoAsync("t2");
            //a.DoAsync("t3");

        }

        #endregion

        #region "TestingBytes"

        //LOGIC IS FROM RIGHT TO LEFT - Little Endian


        private void testBytes()
        {
            File.Delete(e1dbPath);

            //if (_txxx == null)
            //    _txxx = new STSdbMTL_TestManager(e1dbPath);
            if (_txxx == null)
                _txxx = new STSdbMTL_TestManager(@"D:\temp\STS\xxx.db");
            

            //using (var tran = _txxx.Engine.GetTransaction())
            //{
            //    //tran.Insert<int, int>("t1", 2, 1);
            //    //tran.Insert<int, int>("t1", 1, 2);
            //    //tran.Insert<int, int>("t1", 3, 3);

            //    tran.Insert<byte[], int>("t1", new byte[] { 0, 0, 0, 1, 0, 0, 0, 2 }, 1);
            //    tran.Insert<byte[], int>("t1", new byte[] { 0, 0, 0, 1, 0, 0, 0, 1 }, 2);
            //    tran.Insert<byte[], int>("t1", new byte[] { 0, 0, 0, 1, 0, 0, 0, 3 }, 3);

            //    //tran.Insert<byte[], int>("t1", new byte[] { 3, 2, 2 }, 1);
            //    //tran.Insert<byte[], int>("t1", new byte[] { 4, 3, 1 }, 2);
            //    //tran.Insert<byte[], int>("t1", new byte[] { 5, 1, 3 }, 3);

            //    tran.Commit();
            //}

            using (var tran = _txxx.Engine.GetTransaction())
            {
                foreach (var tr in tran.SelectForward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ, new byte[] { 1, 4, 0, 0, 1, 4, 0, 2 }))
                {
                    Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                }

                //foreach (var tr in tran.SelectForward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 2))
                //{
                //    Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                //}

                //foreach (var tr in tran.SelectForward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ, new byte[] { 4, 0, 2 }))
                //{
                //    Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                //}

                //Console.WriteLine("---");

                //foreach (var tr in tran.SelectForward<byte[], int>("t1", STSdb.MTL.eSelectMode.READ, new byte[] { 2, 0 }))
                //{
                //    Console.WriteLine("K: {0}; V: {1}", tr.Key, tr.Value);
                //}
            }

        }
        #endregion

        #region " Simple Backup"

        private void BackUp()
        {
            //_txxx = new STSdbMTL_TestManager(@"D:\temp\STS\db_GM_blazeTest_V1.db");
            _txxx = new STSdbMTL_TestManager(e1dbPath);
            STSdb.MTL.Backup.Backup bp = _txxx.Engine.Backup(@"D:\temp\STS\bup.txt");
            bp.StartBackup();
        }

        private void RestoreUp()
        {
            //File.Delete(@"D:\temp\STS\xxx.db");
            //_txxx = new STSdbMTL_TestManager(@"D:\temp\STS\db_GM_blazeTest_V1.db");
            _txxx = new STSdbMTL_TestManager(@"D:\temp\STS\db_GM_blazeTest_V1.db");
            STSdb.MTL.Backup.Backup bp = _txxx.Engine.Backup(@"D:\temp\STS\backup.txt");
            bp.RestoreBackup();
        }

        #endregion

        #region "Testing nested read locators"

        private void TestNestedRL()
        {
            File.Delete(e1dbPath);

            _txxx = new STSdbMTL_TestManager(e1dbPath);

            using (var tran = _txxx.Engine.GetTransaction())
            {
                for (int i = 0; i < 10; i++)
                {
                    tran.Insert<int, int>("t1", i, i);
                }

                tran.Commit();
            }

            using (var tran = _txxx.Engine.GetTransaction())
            {
                STSdb.MTL.TableRow<int,int> tr1;
                int i=9;
                foreach(var tr in tran.SelectForward<int,int>("t1",STSdb.MTL.eSelectMode.READ))
                {
                    Console.WriteLine(String.Format("I K: {0}; V: {0}",tr.Key,tr.Value));
                    tr1 = tran.Select<int,int>("t1",STSdb.MTL.eSelectMode.READ,i);
                    Console.WriteLine(String.Format("I1 K: {0}; V: {0}", tr1.Key, tr1.Value));
                    i--;
                }
            }
        }

        //Result
        /*
         * I K: 0; V: 0
            I1 K: 9; V: 9
            I K: 1; V: 1
            I1 K: 8; V: 8
            I K: 2; V: 2
            I1 K: 7; V: 7
            I K: 3; V: 3
            I1 K: 6; V: 6
            I K: 4; V: 4
            I1 K: 5; V: 5
            I K: 5; V: 5
            I1 K: 4; V: 4
            I K: 6; V: 6
            I1 K: 3; V: 3
            I K: 7; V: 7
            I1 K: 2; V: 2
            I K: 8; V: 8
            I1 K: 1; V: 1
            I K: 9; V: 9
            I1 K: 0; V: 0
         */

        #endregion

        #region "Testing non-generics transaction"

        private void NonGener()
        {
            File.Delete(e1dbPath);
          

            STSdb.MTL.STSdbMTLengine e = new STSdb.MTL.STSdbMTLengine(e1dbPath);
            STSdb.MTL.Engines.AddEngine("TestEngine", e);
            

            using (var tran = STSdb.MTL.Engines.GetEngine("TestEngine").GetTransaction())
            {
                for (int i = 0; i < 10; i++)
                {
                    tran.Insert<int, int>("t1", i, i);
                }

                tran.Commit();
            }

            /////////////////////////////////////////

            //STSdb.MTL.Engines._RMQC.ExecuteCommand(new STSdb.MTL.RemoteCommand()
            //{
            //    EngineName = "TestEngine",
            //     Command = "",
            //      Parameters 
            //});


            

            using (var tran = STSdb.MTL.Engines.GetEngine("TestEngine").GetTransaction())
            {
                var td = STSdb.MTL.Engines.GetEngine("TestEngine").Scheme.GetTableDefinition("t1");

                string sss = tran.NonGenerics.Select("t1",Type.GetType(td[0]),Type.GetType(td[1]),"READ","5456");

                string sss1 = tran.NonGenerics.SelectForward("t1", Type.GetType(td[0]), Type.GetType(td[0]), "READ", 1000);

                string sss2 = tran.NonGenerics.SelectForwardStartKey("t1", Type.GetType(td[0]), Type.GetType(td[0]), "READ","5",3);

                ////var td = 
                //foreach (var tr in tran.NonGenerics.SelectForward("t1", Type.GetType("System.Int32"), Type.GetType("System.Int32"), "READ", 1000))
                //{
                //    Console.WriteLine(tr);
                //}
            }



        }

        #endregion

        #region "Testing Backup 2"

        private void TestBackup2()
        {
           
            
        }

        #endregion


        #region "test asin issue"

        STSdb.Data.StorageEngine xse = null;
        STSdb.Data.XTable<long, byte[]> writeTableT1 = null;
        STSdb.Data.XTable<long, byte[]> writeTableT2 = null;
        STSdb.Data.XTable<long, byte[]> writeTableT3 = null;
        volatile bool finished = false;

        /// <summary>
        /// Function Main
        /// </summary>
        private void Start()
        {
            File.Delete(e1dbPath);
            xse = StorageEngine.FromFile(e1dbPath);

            writeTableT1 = xse.Scheme.CreateXTable<long, byte[]>(new Locator("t1"));
            xse.Scheme.Commit();
            writeTableT2 = xse.Scheme.CreateXTable<long, byte[]>(new Locator("t2"));
            xse.Scheme.Commit();
            writeTableT3 = xse.Scheme.CreateXTable<long, byte[]>(new Locator("t3"));
            xse.Scheme.Commit();


            System.Threading.Thread trW1 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Write));
            System.Threading.Thread trW2 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Write));
            System.Threading.Thread trW3 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Write));

            System.Threading.Thread tr2 = new System.Threading.Thread(new System.Threading.ThreadStart(Read));

            //REMARK BLOCK 2 and UNREMARK BLOCK 1, to get no issue

            //BLOCK 1
            //trW1.Start("t1");
            //trW2.Start("t2");
            //trW3.Start("t3");
            //System.Threading.Thread.Sleep(3000);
            //tr2.Start();
            ///////////////////////////   END OF BLOCK 1

            //REMARK BLOCK 1 and UNREMARK BLOCK 2, to get CountBefore == countAfter issue (Begin-End Invoke is used)

            //BLOCK 2
            Action w1 = (() => { Write("t1"); });
            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(w1);
            //STSdb.MTL.Utils.Async.AsyncOperationsExtensions.MakeOperationAsync(w1);
            //w1.DoAsync();
            Action w2 = (() => { Write("t2"); });
            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(w2);
            //STSdb.MTL.Utils.Async.AsyncOperationsExtensions.MakeOperationAsync(w2);
            //w2.DoAsync();
            Action w3 = (() => { Write("t3"); });
            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(w3);
            //STSdb.MTL.Utils.Async.AsyncOperationsExtensions.MakeOperationAsync(w3);
            //w3.DoAsync();
            //System.Threading.Thread.Sleep(3000);
            Action r1 = (() => { Read(); });
            STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(r1);
            //STSdb.MTL.Utils.Async.AsyncOperationsExtensions.MakeOperationAsync(r1);
            //w1.DoAsync();
            ///////////////////////////   END OF BLOCK 2

            //WHERE DoAsync is an extension:
            /*
             *  public static void DoAsync(this Action f)
                {
                    f.BeginInvoke(x => { f.EndInvoke(x); }, null);
                }
             */
        }

        //private void Write(object oTableName)
        //{
        //    string tableName = oTableName.ToString();

        //    ulong countBefore = 0;
        //    ulong countAfter = 0;

        //    Random rnd = new Random();
        //    byte[] bt = new byte[150];

        //    STSdb.Data.XTable<long, byte[]> writeTable = null;

        //    for (long i = 0; i < 100000; i++)
        //    {
        //        lock (xse.Scheme.SyncRoot)
        //            writeTable = xse.Scheme.OpenXTable<long, byte[]>(new Locator(tableName));

        //        countBefore = writeTable.Count;

        //        rnd.NextBytes(bt);

        //        //lock (xse.Scheme.SyncRoot)
        //        //{
        //            //countBefore = writeTable.Count;
        //            writeTable[i] = bt;

        //         //   lock (xse.Scheme.SyncRoot)        //just for test, in case of BeginEnd Invoke doesn't help
        //                writeTable.Commit();
        //            //countAfter = writeTable.Count;
        //        //}

        //        countAfter = writeTable.Count;

        //        //Console.WriteLine(String.Format("Before: {0}; After: {1}", countBefore, countAfter));

        //        if (countBefore == countAfter)
        //        {
        //            //This point shouldn't be reached. But it reaches.
        //            //breakpoint inside
        //        }

        //        //writeTable.Close();
        //        //writeTable = null;
        //    }

        //    finished = true;

        //    Console.WriteLine("done write");
        //}

        private object xLock = new object();

        private void Write(object oTableName)
        {
            string tableName = oTableName.ToString();

            ulong countBefore = 0;
            ulong countAfter = 0;

            Random rnd = new Random();
            byte[] bt = new byte[150];

            STSdb.Data.XTable<long, byte[]> writeTable = null;

            for (long i = 0; i < 100000; i++)
            {
                lock (xLock)
                {
                    writeTable = xse.Scheme.OpenXTable<long, byte[]>(new Locator(tableName));

                    countBefore = writeTable.Count;

                    rnd.NextBytes(bt);

                    //lock (xse.Scheme.SyncRoot)
                    //{
                    //countBefore = writeTable.Count;
                    writeTable[i] = bt;

                    //   lock (xse.Scheme.SyncRoot)        //just for test, in case of BeginEnd Invoke doesn't help
                    writeTable.Commit();
                    //countAfter = writeTable.Count;
                    //}

                    countAfter = writeTable.Count;

                    //Console.WriteLine(String.Format("Before: {0}; After: {1}", countBefore, countAfter));

                    if (countBefore == countAfter)
                    {
                        //This point shouldn't be reached. But it reaches.
                        //breakpoint inside
                    }

                    writeTable.Close();
                    writeTable = null;
                }
            }

            finished = true;

            Console.WriteLine("done write");
        }

        private void Read()
        {
            STSdb.Data.XTable<long, byte[]> readTable = null;
            ulong cnt = 0;

            while (!finished)
            {
                lock (xLock)
                {
                    readTable = xse.Scheme.OpenXTable<long, byte[]>(new Locator("t1"));

                    //lock (xse.Scheme.SyncRoot)
                    cnt = readTable.Count;
                }

                //Console.WriteLine(String.Format("Read: {0}", cnt));

                //System.Threading.Thread.Sleep(50);
            }

            Console.WriteLine("done read");
        }

        #endregion



        #region "test async issue MTL"

        //STSdb.MTL.STSdbMTLengine xse = null;
        //string locatorName = "t1";
        //volatile bool finished = false;

        ///// <summary>
        ///// Function Main
        ///// </summary>
        //private void Start()
        //{

        //    File.Delete(e1dbPath);

        //    //STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = false;
        //    STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = true;
        //    STSdb.MTL.StsTablesCompactor._MIN_QUANTITY_FOR_COMPACTION_START = 100;
        //    STSdb.MTL.StsTablesCompactor.COMPACTION_DIFF_BETWEEN_COMPACTS_IN_MINUTES = 0;

        //    xse = new STSdb.MTL.STSdbMTLengine(e1dbPath);

        //    System.Threading.Thread trW1 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Write));
        //    System.Threading.Thread trW2 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Write));
        //    System.Threading.Thread trW3 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Write));

        //    System.Threading.Thread tr2 = new System.Threading.Thread(new System.Threading.ThreadStart(Read));

        //    trW1.Start("t1");
        //    trW2.Start("t2");
        //    trW3.Start("t3");
        //    System.Threading.Thread.Sleep(1000);
        //    tr2.Start();


        //    //Action w1 = (() => { Write("t1"); });
        //    //w1.DoAsync();
        //    //Action w2 = (() => { Write("t2"); });
        //    //w2.DoAsync();
        //    //Action w3 = (() => { Write("t3"); });
        //    //w3.DoAsync();
        //    //System.Threading.Thread.Sleep(1000);
        //    //Action r1 = (() => { Read(); });
        //    //w1.DoAsync();
        //}

        //private void Write(object otableName)
        //{
        //    string tableName = otableName.ToString();
        //    ulong countBefore = 0;
        //    ulong countAfter = 0;

        //    Random rnd = new Random();
        //    byte[] bt = new byte[150];

        //    for (long i = 0; i < 100000; i++)
        //    {
        //        using (var tran = xse.GetTransaction())
        //        {

        //            countBefore = tran.Count<long, byte[]>(tableName, true);

        //            rnd.NextBytes(bt);

        //            tran.Insert<long, byte[]>(tableName, i, bt);
        //            tran.Commit();

        //            countAfter = tran.Count<long, byte[]>(tableName, true);

        //            //Console.WriteLine(String.Format("Before: {0}; After: {1}", countBefore, countAfter));

        //            if (countBefore == countAfter)
        //            {
        //                //Here can be the issue,  
        //                //breakpoint inside
        //            }
        //        }
        //    }

        //    finished = true;

        //    Console.WriteLine("done write");
        //}

        //private void Read()
        //{
        //    ulong cnt = 0;

        //    while (!finished)
        //    {
        //        using (var tran = xse.GetTransaction())
        //        {
        //            cnt = tran.Count<long, byte[]>(locatorName, false);

        //            //var tr = tran.Select<long, byte[]>(locatorName, STSdb.MTL.eSelectMode.READ, 1);
        //        }
        //    }

        //    Console.WriteLine("done read");
        //}

        #endregion

        #region "Insert 1 mln"

        private void Insert1mln()
        {
            File.Delete(e1dbPath);
            _txxx = new STSdbMTL_TestManager(e1dbPath);

            using (var tran = _txxx.Engine.GetTransaction())
            {
                for (int i = 0; i < 1000000; i++)
                {
                    tran.Insert<int, byte>("t1", i, 1);
                }

                tran.Commit();
            }
        }

        #endregion

        #region "Select Forward Test"
        private void TestSelectForward()
        {
            File.Delete(e1dbPath);
            if (_txxx == null)
                _txxx = new STSdbMTL_TestManager(e1dbPath);

            using (var tran = _txxx.Engine.GetTransaction())
            {
                for (int i = 0; i < 50; i++)
                {
                    tran.Insert<int, int>("t1", i, i);
                }

                tran.Commit();

                //foreach (var tr in tran.SelectForward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 3))   //>=
                //{
                //    Console.WriteLine("Key: {0}", tr.Key);
                //}

                //foreach (var tr in tran.SelectForward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 3,10))   //>= <=
                //{
                //    Console.WriteLine("Key: {0}", tr.Key);
                //}

                ////////////////////


                //foreach (var tr in tran.SelectForward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 45, STSdb.MTL.eCompareModifierUp.Bigger))
                //{
                //    Console.WriteLine("Key: {0}", tr.Key);
                //}

                //foreach (var tr in tran.SelectForward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 45, STSdb.MTL.eCompareModifierUp.BiggerOrEqual, 70, STSdb.MTL.eCompareModifierDown.Less))
                //{
                //    Console.WriteLine("Key: {0}", tr.Key);
                //}

                //foreach (var tr in tran.SelectBackward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 45, STSdb.MTL.eCompareModifierDown.Less).Take(10))
                //{
                //    Console.WriteLine("Key: {0}", tr.Key);
                //}

                //foreach (var tr in tran.SelectBackward<int, int>("t1", STSdb.MTL.eSelectMode.READ, 48, STSdb.MTL.eCompareModifierDown.Less, 35, STSdb.MTL.eCompareModifierUp.Bigger))
                //{
                //    Console.WriteLine("Key: {0}", tr.Key);
                //}


            }
        }
        #endregion


        private void btTest1_Click(object sender, RoutedEventArgs e)
        {

            TestSelectForward();
            return;

            //Start();
            //Insert1mln();
            //return;
            //TestBackup2();
            //return;
            //NonGener();
            //return;

            //TestNestedRL();
            ////BackUp();
            ////RestoreUp();
            ////return;
            ////testBytes();
            //return;
        //    if(se == null)
        //        File.Delete(e1dbPath);

        //    InitTable_PC();
        //    return;
            //Insert1000Rows();

            //Action a100 = () =>
            //{
            //    StartSelectOfThis1000("1");
            //};

            //a100.DoAsync();

            //return;
            //InitTable();
            //StartManyThreads();
            //return;
            //StarttestAsyncCompacting();
            //BigObjecT();

            //File.Delete(e1dbPath);
            //testDataBreezingV2("t1");
            //return;
            //STSdb.MTL.Utils.Files.FileLogger.ActivateFileLogger(String.Empty);

            // //DateTime;  TableName;  Table1ReadyToSave;1 - Table 1 Saved or 0;    Table2ReadToSave;0/1 - Table 2 Save;  Compactor tableName; 1 - Started; 1 - Finished; quantity records

            //STSdb.MTL.Utils.Files.FileLogger.WriteToFileLoggerAscii(
            //        String.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};{10};\r\n",
            //        "DateTime",
            //        "TableName",
            //        "Table_1_Ready2Save",    //Table1ReadyToSave
            //        "Table_1_Saved",  //1 - Table 1 Saved or 0
            //        "Table_2_Ready2Save",     //Table2ReadyToSave,
            //        "Table_2_Saved",  //1 - Table 2 Saved or 0
            //        "CompactorTable",                              //Compactor tableName
            //        "CompactorStarted",                              //Compactor started
            //        "CompactorFinished",                                //Compactor finished
            //        "RecQuantity",
            //        "ManagedThreadId"
            //        ));

            //Action a1 = () =>
            //    {
            //        testDataBreezing_UpdatingOneValue("t1");
            //    };

            //a1.DoAsync();

            //Action a2 = () =>
            //{
            //    testDataBreezing_UpdatingOneValue("t2");
            //};

            //a2.DoAsync();

            //Action a3 = () =>
            //{
            //    testDataBreezing_UpdatingOneValue("t3");
            //};

            //a3.DoAsync();


            //Action a1 = () =>
            //    {
            //        testDataBreezingV2("t1");
            //    };

            //STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a1);
            ////a1.DoAsync();

            //Action a2 = () =>
            //{
            //    testDataBreezingV2("t2");
            //};

            //STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a2);
            ////a2.DoAsync();


            //Action a3 = () =>
            //{
            //    testDataBreezingV2("t3");
            //};

            //STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a3);
            ////a3.DoAsync();

            //System.Threading.Thread.Sleep(2000);

            // Action a4 = () =>
            //{
            //    parallelReadWithDataBreazingV2();
            //};

             //STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a4);
             //a4.DoAsync();

            

            //testDataBreezing_UpdatingOneValue();

            //SwitchingRawFiles();

            //insert10Mln();

            //FileSystemTest();

            //NativeSTSCompact();
            //NativeSTSCompact_V2();

            //CreateEmptyTables();
            //TestReadLocatorHandler();
            //TestExhale();

            //TestInsertAndDeleteFile();


            //TestSomeInsertsAndSomeDeletesAndFileSize();


            //InsertRandomValues();
            //CopyToNewTable();

            //InsertSequentialValues();

            //TestSelectSomething();


            //TestEmptyTablesSize();

            //this.TestingSmallTransactionsV5();
            //FetchDRDData();


            //this.TestGoto();

            //TestValueAsObject();

            //this.TestTransactionLog();

            //this.CreateMultipleSnapshots();

            //this.test_startAO();

            //CreateEmptyTables(1000);
            //this.TestFileSizes();

            //this.TestRemoteCommands();

            //this.TestCreateDbFromMultipleFiles();

            //this.TestSchemas();

            //this.TestSnapshots();

            //this.StartMIT();

            //this.DoTypeConversion();

            //this.InitTables();

            //int mbc = Encoding.Unicode.GetMaxByteCount(32);
            //int mbc =  Encoding.ASCII.GetMaxByteCount(32);
            //mbc = Encoding.UTF8.GetMaxByteCount(32);

            //byte[] njh = System.Text.Encoding.UTF8.GetBytes(String.Empty);
            //byte[] njh = new byte[] { };

            //this.InsertStrings();
            //this.InsertInts();
            //this.InsertBytes(Encoding.UTF8);
            //this.InsertBytes(Encoding.ASCII);

            //this.SelectBytesForward(Encoding.UTF8);
            //Console.WriteLine("-----");
            //this.SelectBytesBackward(Encoding.UTF8);

            //this.InsertAndSelectString();


            //if (_sts_engine == null)
            //    _sts_engine = new STSdb.MTL.STSdbMTLengine(dbPath);

            //this.test2();
            //this.test_commitInOneThread_rollBackInAnother();
            //this.testIdentityAutoIncrement();

            //this.FillDb_WithCars();

            //this.SupportNewIndex();

            //this.SearchingCarByLicensePlate();

            //this.CreateManyTabels();


            
            
        }



        private void btTest2_Click(object sender, RoutedEventArgs e)
        {



            return;

            //Action a100 = () =>
            //    {
            //        if (_txxx == null)
            //            _txxx = new STSdbMTL_TestManager(e1dbPath);

            //        Random rnd = new Random();
            //        byte[] toInsert = new byte[150];

            //        long k = 1000000;
            //        using (var tran = _txxx.Engine.GetTransaction())
            //        {
            //            for (int i = 0; i < 2000; i++)
            //            {
            //                rnd.NextBytes(toInsert);
            //                try
            //                {
            //                    tran.Insert<long, byte[]>("t1", k, toInsert);
            //                    tran.Commit();
            //                }
            //                catch
            //                {

            //                }
            //                k++;
            //            }
            //        }
            //    };

            //STSdb.MTL.Utils.Async.AsyncOperations.DoAsync(a100);
            //a100.DoAsync();

            //Action a100 = () =>
            //{
            //    Insert200More();

            //    StartSelectOfThis1000("2");
            //};

            //a100.DoAsync();


            //if (_txxx == null)
            //    _txxx = new STSdbMTL_TestManager(e1dbPath);

            //using (var tran = _txxx.Engine.GetTransaction())
            //{
            //    var c = tran.Count<long, byte[]>("t1");
            //    Console.WriteLine("t1" + ":" + c.ToString());
            //    c = tran.Count<long, byte[]>("t2");
            //    Console.WriteLine("t2" + ":" + c.ToString());
            //}
            //select10mln();
        }




        private void btTest3_Click(object sender, RoutedEventArgs e)
        {

            File.Delete(e1dbPath);

            STSdb.MTL.StsTablesCompactor.COMPACTOR_IS_ACTIVATED = false;
            if (_txxx == null)
                    _txxx = new STSdbMTL_TestManager(e1dbPath);

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            using (var tran = _txxx.Engine.GetTransaction())
            {

                //TEST 1
                //DateTime dt = new DateTime(1970, 1, 1);
                //for (int i = 0; i < 1000000; i++)
                //{

                //    tran.Insert<byte[], byte[]>("t1", dt.Ticks.To_8_bytes_array_BigEndian(), new byte[] { 1 });
                //    dt = dt.AddHours(1);
                //}
                //OR
                //DateTime dt = new DateTime(1970, 1, 1);
                //for (int i = 0; i < 1000000; i++)
                //{                  

                //    tran.Insert<long, byte[]>("t1", dt.Ticks, new byte[] { 1 });
                //    dt = dt.AddHours(1);
                //}

                //tran.Commit();

                ///////////////////////////////////////////////////////////////////////////////////////////////////

                //TEST 2
                //Random rnd = new Random();
                //int vvv = 0;
                //for (int i = 0; i < 1000000; i++)
                //{
                //    vvv = rnd.Next(Int32.MaxValue);
                //    tran.Insert<byte[],byte[]>("t1",vvv.To_4_bytes_array_BigEndian(), vvv.To_4_bytes_array_BigEndian());
                //}
                //OR
                Random rnd = new Random();
                int vvv = 0;
                for (int i = 0; i < 1000000; i++)
                {
                    vvv = rnd.Next(Int32.MaxValue);
                    tran.Insert<int, byte[]>("t1", vvv, new byte[] {1});
                }

                tran.Commit();

                //TEST 3
                //for (int i = 0; i < 1000000; i++)
                //{
                //    tran.Insert<byte[], byte[]>("t1", i.To_4_bytes_array_BigEndian(), new byte[] { 1 });
                //}
                //OR
                //for (int i = 0; i < 1000000; i++)
                //{
                //    tran.Insert<int, byte[]>("t1", i, new byte[] { 1 });
                //}

                //tran.Commit();
            }

            sw.Stop();
            Console.WriteLine("INSERT IS DONE" + sw.ElapsedMilliseconds.ToString());
        }
    }
}
